angular - 将函数传递给子组件 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”不是函数。如何在子组件中传递我的方法?
解决方案
我认为您必须像这样使用 .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>
推荐阅读
- python - 打开 Json,替换值并运行 json.load
- javascript - 如何在 5 分钟的可控时间内显示一条消息
- c# - 在子类型接口和它的基类型接口之间转换,然后再转换回来,是一件坏事吗?
- python - 如何使用python将唯一值写入csv
- python-3.x - 计算两列之间的回归,然后移动到下一列,然后是接下来的两列,依此类推
- sql - PostgreSQL 中日期的数据类型
- excel - 如何在同一列(如 A2-A1)但在 PowerBI 中减去两个时差行
- ios - Swift - 向下滑动时如何分页
- reactjs - 我的网址在 Postman 中有效,但在浏览器中使用时无效?
- twitter - 是否有可能知道特定推文的来源国?