Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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.

How do I get access to the component scope from here?

like image 788
wesley.ireland Avatar asked Sep 07 '16 13:09

wesley.ireland


1 Answers

Add .bind(this) to fix this

element.addEventListener("click", this.onclick.bind(this), false);
like image 55
Günter Zöchbauer Avatar answered Nov 08 '22 11:11

Günter Zöchbauer