Patrick Patrick - 1 year ago 53
AngularJS Question

Angular 2 & Typescript: Cannot access class instance from event handler

My use case requires me to add several copies of a child component to a template programmatically (think: iterating through an array with

*ngFor="let childComponent of componentArray"
). The children components all emit a
event; the twist is that each of these components has a different event handler within the parent component. Trying to be clever, I decided to store the event handler as a property of each member of
. So my template is now something like:

<my-cmp *ngFor="let childComponent of componentArray" (select)="childComponent.callback()"></my-cmp>

My model contains:

componentArray = [{data:0, callback:this.onSelect0}, {data:1, callback:this.onSelect1}];

onSelect0(){/*do stuff specific to childComponent 0*/}
onSelect1(){/*do stuff specific to childComponent 1*/}

is a reference to the class method I would like that particular childComponent's
event to trigger.
is triggered properly; the problem is that from it I cannot access the rest of my component because
in that context refers to the
during that iteration of the loop.

It sounds more confusing than it is. I've found a workaround but it seems really clunky (I store the class instance as a property in each member of componentArray). I've made a plunkr accessible from Basically my question is: if I pass the event handler as an object property (
above), how can I access my class instance? Any feedback is welcome.


That's default JS/TS behavior if you pass a method reference directly. You can either use bind like methodName.bind(this) or a fat arrow function like () => methodName() to retain the scope of this.

In your Plunker just change this line

  private thing = {name:'ThingOne', onSelect: this.handlerOne };


  private thing = {name:'ThingOne', onSelect:() => this.handlerOne() };

Plunker example