如何处理 PrimeNG p-fullCalendar 的自定义按钮点击事件?

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

我正在使用 p-fullCalendar 控件来显示约会。

我想在页眉中添加自定义按钮以添加新约会。

我已经通过在选项 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.
          }
        }
      }
    };

html 是:

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

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

按钮显示正常,点击事件也被触发。

但是如何处理这个按钮的点击事件才能显示模态对话框呢?

点击事件中的 this 是按钮本身:

您可以设置 _self = this 并处理这个 _self 变量

ngOnInit() {
    let _self = this;
    this.options = {
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'addAppointmentButton, month,agendaWeek,agendaDay'
      },
      customButtons: {
        addAppointmentButton:{
          text:"New appointment",
          click: (r) => {
              console.log(_self);
          }
        }
      }
    };

将点击事件绑定到组件方法并绑定(this):

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

已测试并有效。这样你就不会失去范围。