Search code examples
angularprimengprimeng-calendar

How to handle custom button click event for PrimeNG p-fullCalendar?


I am using the p-fullCalendar control to display appointments.

I want to add a custom button in the header to add a new appointment.

I have done that by specifying it in the options as per full calendar docs:

export class AppointmentsComponent implements OnInit {

  events: any[];
  options: any;
  displayAddAppointment: boolean;

  constructor() { }

  ngOnInit() {

    this.options = {
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'addAppointmentButton, month,agendaWeek,agendaDay'
      },
      customButtons: {
        addAppointmentButton:{
          text:"New appointment",
          click: r=> {
            //this works but displayAddAppointment within the component is inaccessible.
            //I would like to display a modal dialog to add a new appointment from this.
          }
        }
      }
    };

the html being :

<div>
 <p-fullCalendar [events]="events" [options]="options"></p-fullCalendar>

 <p-dialog header="Schedule new appointment" 
         [(visible)]="displayAddAppointment" 
         modal="modal">
 </p-dialog>
<div>

The button is displayed fine and the click event gets fired too.

But how do I handle the click event of this button so that I can display the modal dialog?

The this within the click event is the button itself:

thiswithinclickevent


Solution

  • Bind the click event to a component method and bind(this):

    addAppointmentButton: {
        text: 'New appointment',
        click: this.click.bind(this)
    }
    // ...
    click() {
        this.displayAddAppointment = !this.displayAddAppointment;
    }
    

    Tested and works. This way you don't lose scope.