回调函数无权访问组件中的任何内容。我认为我必须绑定“ this”,但是我在执行该操作的位置上有点迷失了。 https://stackblitz.com/edit/angular-tzv5nl
在我的html模板中,我有一个按钮,我在其中传递了回调函数作为参数:
<button (click)="primaryAction('test',furtherAction1)">Action<button>
在我的组件中,我具有功能
primaryAction(string,callback){
this.primaryActionDone = "Done";
callback()
}
furtherAction1(){
alert("furtherAction1 called but has no access to 'this'");
this.furtherAction1Done= "Done"; //Error: Cannot set property 'furtherAction1Done' of undefined
this.furtherAction2()
}
furtherAction2(){
this.furtherAction2Done= "Done";
}
furtherAction1无法访问this.furtherAction1Done或this.furtherAction2()。
现在我该如何在回调函数中使用适当的“ this”?
答案 0 :(得分:1)
这只是一个范围问题。
要将上下文重新绑定到函数,请使用call
primaryAction(string,callback){
this.primaryActionDone = "Done";
callback.call(this)
}