在我的组件中,我得到了一个包含函数引用的对象。但是当我将它传递给组件的 HTML 并执行时,它无法访问函数范围之外的任何其他属性。有什么办法可以做到这一点吗?
这是我的代码:
button = {label: 'My action', action: this.doStuff }
doStuff(){
if(this.userService.IsUserLoggedIn){ // Cannot read property 'IsUserLoggedIn' of undefined
//do stuff
}
}
<button (click)="button.action()">{{button.label}}</button>
我尝试添加一个附加函数来将 this
绑定(bind)到函数,但没有成功。
<button (click)="exec(button.action)">{{button.label}}</button>
exec(func: Function){
func.bind(this);
func();
}
对任何错误表示歉意
最佳答案
那是因为在声明按钮对象时必须绑定(bind)上下文:
button = { label: 'My action', action: this.doStuff.bind(this) }
(我创建了 obj.condition
,以便您在删除 .bind(this)
时看到类似的错误)
关于javascript - 方法在传递给组件的 HTML 时没有上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363063/