简体   繁体   中英

How to emit event from component loop to main parent angular 5

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM