[英]Angular 2: How do you access component variables within an event (scope issue)
I have a click event on my component, that needs to access private variables from the component itself. 我的组件上有一个click事件,需要从组件本身访问私有变量。 However I seem to be running into a scoping issue: the keyword
this
no longer refers to the component's scope but rather the scope of the event. 不过,我似乎遇到了一个范围问题:关键字
this
不再是指该组件的范围,而是事件的范围。 Help! 救命!
onclick(event){
for(var i = 0; i < this.arr.length; i++) { ... }
}
In the above example, this.arr
is undefined because it does not belong to the event scope. 在上面的示例中,
this.arr
未定义,因为它不属于事件范围。
How do I get access to the component scope from here? 如何从此处访问组件范围?
添加.bind(this)
来解决this
element.addEventListener("click", this.onclick.bind(this), false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.