Angular 模板中传入的回调函数无法访问组件
Callback function passed in Angular template has no access to component
回调函数无权访问组件中的任何内容。我假设我必须绑定 "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"?
这只是范围问题。
要将上下文重新绑定到函数,请使用 call
primaryAction(string,callback){
this.primaryActionDone = "Done";
callback.call(this)
}
回调函数无权访问组件中的任何内容。我假设我必须绑定 "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"?
这只是范围问题。
要将上下文重新绑定到函数,请使用 call
primaryAction(string,callback){
this.primaryActionDone = "Done";
callback.call(this)
}