简体   繁体   English

Angular 2:如何访问事件中的组件变量(范围问题)

[英]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.

相关问题 如何访问链接中的角度指令隔离范围变量? - How do you access angular directive isolated scope variables in link? 如何从angular.js的指令中访问作用域变量? - How to access scope variables from within a directive in angular.js? 您如何访问多个指令的作用域变量? - How do you access scope variables of a number of directives? 如何从Angular中的回调访问外部作用域变量? - How do I access outer scope variables from a callback in Angular? 循环内的 Vue 2 组件访问循环 - 实例/范围问题 - Vue 2 Component Access Loop within a Loop - instance/scope issue 如何在具有输入的子组件中访问父组件的for循环? - How do you access the for loop of the parent component within a child component which has the inputs? 如何在用TypeScript编写的Angular控制器上访问范围值(在测试中)? - How do you access scope values (in your tests) on an Angular controller written in TypeScript? 如何在HighCharts中的单击函数中访问外部范围变量 - How to access outer scope variables within a click function in HighCharts 您如何在json范围内进行评估? - How do you do an eval within the scope of a json? 如何从事件处理程序中访问组件的prop值? - How do I access a component's prop value from within an event handler?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM