This is a follow up to this question that was about function references between components.
If I have a ParentComponent:
export class ParentComponent {
public myParentVariable = 'Hello world';
test() {
console.log(this.myParentVariable);
}
public options: any[] = [
{label: 'Item 1', onClick: this.test},
{label: 'Item 3', onClick: this.test},
{label: 'Item 6', onClick: this.test},
{label: 'Item 2', onClick: this.test}
];
}
As you can see I pass a reference to test in the onClick property.
Then I have a ChildComponent which I pass options to from the ParentComponent:
<child [options]="options"></child>
And in child I have a list:
<ul class="dropdown-list">
<li *ngFor="#option of options" (click)="option.onClick()"></li>
</ul>
As you can see in the template I then call onClick from before as (click)="option.onClick()".
The problem now is that from here it has no idea what this.myParentVariable is anymore since we're just passing a reference to test. So instead I want to make onClick into an EventEmitter which I can then call .emit() on, so that we execute test with the correct data binding, like shown here.
But since I pass down an array containing objects that contains a property that reference a function, I'm not quite sure how to make the single onClick property of each object an EventEmitter.
I tried making the entire options into an outputted EventEmitter but that failed miserably.
Any ideas on how to achieve this?