In the scenario I'm working on, I need to dynamically add multiple instances of a child component to a template. Each of these child components emits a 'select' event, and each one requires a different event handler within the parent component. To handle this, I decided to store the event handler as a property of each item in an array called 'componentArray'. As a result, my template now looks like this:
<my-cmp *ngFor="let childComponent of componentArray" (select)="childComponent.callback()"></my-cmp>
My model is structured as follows:
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*/}
The 'callback' property holds a reference to the specific method I want that particular child component's 'select' event to trigger. While the 'callback' function is being triggered correctly, the issue arises when trying to access other components within the parent component. The context of 'this' within the callback refers to the 'component' during that specific iteration of the loop.
Although I found a workaround by storing the class instance as a property in each item of 'componentArray', it feels cumbersome. I have a Plunkr demo available at http://plnkr.co/edit/VxxCR8hjUsxQ3SABWe8E?p=preview to illustrate my issue. Essentially, my question is: if I pass the event handler as an object property ('childComponent.callback' in the example above), how can I access my class instance? Any insights or suggestions would be appreciated.