I have an angular2 app where i have a Full Calendar component. I want to display a dialog on click of a full calendar event using the eventClick callback. I have the following code to do this:
export class ScheduleComponent implements OnInit{
events: CalendarEvent[];
display: boolean;
tables: SelectItem[];
selectedTable: string;
ngOnInit(){
this.display = false;
this.scheduleService.GetAllEvents().subscribe((data: CalendarEvent[]) =>
{
this.events = data;
var calendar: JQuery = $("#calendar");
(<any>calendar).fullCalendar({
eventClick: function(event) {
this.display = true;
return false;
}
});
});
}
}
This is a very simplified version but should give all the information needed.
My problem is that the this.display = true line inside the eventClick callback does not seem to be able to see the display property.
Does anyone know why this is and how i could fix it?
Thanks,
Typically after posting a question, i have now worked out a resolution.
The solution for anyone else struggling with this is to use the 'fat arrow' notation.
So instead of this:
eventClick: function(event) {
this.display = true;
return false;
}
I used this:
eventClick: (event) => {
this.display = true;
return false;
},
Im not too sure how this works as it was just trial and error. So if anyone does know why and can explain it then i would be very interested to find out why.
The challenge you were facing had something to do with scope. At runtime the value of this changes and there fore display wont be accessible.
Lexical scoping is one of the ways you can solve this and thats what you have done above.
You can also bind the context of the method to the this so it executes within that context.
You can do this using the javascript bind method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With