Reputation: 5051
I wrote the below code, where I am looping component to display children
parent.component.ts
tree = [
{
id: 1,
name: 'test 1'
}, {
id: 2,
name: 'test 2',
children: [
{
id: 3,
name: 'test 3'
}
]
}
]
nodeClicked(event) {
console.log(event);
}
parent.component.html
<app-child [tree]="tree" (nodeEmitter)="nodeClicked($event)"></app-child>
child.component.ts
@Input() tree;
@Output() nodeEmitter = new EventEmitter();
clickToEmit() {
this.nodeEmitter.emit(1);
}
child.component.html
<ul>
<li *ngFor="let node of tree">{{ node.name }}</li>
<button (click)="clickToEmit()">Click Me!!!</button>
<app-child [tree]="node.children" (nodeEmitter)="nodeClicked($event)"></app-child>
</ul>
Here, my problem is
I am able to get emitted event in parent.component.html
I am not able to get emitted event from child.component.html to
parent.component.html
I am getting the error as nodeClicked is not defined in child.component.ts
What I am doing wrong here? I wasted so many hours of time on this issue.
Thank you for your help... :-)
Upvotes: 1
Views: 2136
Reputation: 14219
In the child component you need to continue chaining the event up to the parent. Modify your template so that the emitter re-emits when a child event occurs.
<ul>
<li *ngFor="let node of tree">{{ node.name }}</li>
<button (click)="clickToEmit()">Click Me!!!</button>
<app-child [tree]="node.children" (nodeEmitter)="nodeEmitter.emit($event)"></app-child>
</ul>
Upvotes: 4