我为动态生成的按钮分配了一个点击处理程序。我在点击处理程序函数内部调用了回调函数。不幸的是,我收到一条错误消息,指出“回调函数不是函数”。我在下面提供基本代码。
HTML(组件2)-
<button *ngFor="let btn of content.buttons" type="button" (click)="btn.func()" class="{{btn.type}}"><span class="btn-text">{{btn.text}}</span></button>
TS(组件2)-
@Component({
selector: 'app-popup',
})
@Input() content;
我从中传递数据的组件代码-
HTML(组件1)-
<app-popup [content]="popupContent"></app-popup>
TS(组件1)-
this.popupContent = {
"buttons":[{
"text":"OK",
"type":"btn-red",
"func": this.someHandler
}]
};
someCallbackFunction(){
console.log('I am a callback function');
}
someHandler(){
this.someCallbackFunction();
}
当我单击按钮时触发事件时,它将引发此错误-
ERROR TypeError: this.someCallbackFunction is not a function
我也尝试过设置处理程序,如
(click)="btn[func]()"
但是不幸的是,这对我没有用。
请提出解决方案。谢谢:)
尝试通过粗箭头函数调用该函数,那样它应该具有正确的this
上下文。只需更改定义方式即可。
"buttons":[{
"text":"OK",
"type":"btn-red",
"func": () => { this.someHandler(); }
}];
将
"func": this.someHandler
修改为"func": this.someHandler
尝试这样:
buttons =[{
"text":"OK",
"type":"btn-red",
"func" :() => this.someHandler()
}]