首页 > 解决方案 > 将函数传递给子组件 ANGULAR 5

问题描述

我有一个组件“日历”及其子组件“月份”。

export class MonthCalendarComponent  {
  @Input() holidayClicked: (day: Date) => Observable<boolean>;

 dayClicked(day: CalendarMonthViewDay): void {
    this.holidayClicked(day.date).subscribe(isHoliday => {
      if (isHoliday) {
        delete day.cssClass;
      } else {
        day.cssClass = 'cal-day-selected';
      }
    });
    // console.log(this.selectedDays);
  }
}

我有一个方法,我想使用 CalendarComonent 中的 @Input holidayClicked

export class CalendarComponent implements OnInit {
  @ViewChildren(MonthCalendarComponent) months: any[];  
holidayClicked(holiday: Date): Observable<boolean> {

    const username = 'user';
    this.holiday.date = holiday;
    this.holiday.stateVal = this.stateSelected;

    this.calendarService.updateEmployee(username, this.holiday).subscribe();

    this.calendarService.updateEmployee(username, this.holiday).map(x => {});
    return new Observable();
  }
}

肯定有问题,因为我收到错误“holidayClicked”不是函数。如何在子组件中传递我的方法?

标签: angular

解决方案


我认为您必须像这样使用 .bind :

export class MonthCalendarComponent  {
public theBoundCallback: Function;
public theCallback(holiday: Date){
    ...
  }
public ngOnInit(){
    this. theBoundCallback = this. theCallback.bind(this);
  }
  

  @Input() holidayClicked: Function

 dayClicked(day: CalendarMonthViewDay): void {
    this.holidayClicked(day.date).subscribe(isHoliday => {
      if (isHoliday) {
        delete day.cssClass;
      } else {
        day.cssClass = 'cal-day-selected';
      }
    });
    // console.log(this.selectedDays);
  }
}
<child [holidayClicked]="theBoundCallback"></child>


推荐阅读