簡體   English   中英

如何從組件循環向主父角5發射事件

[英]How to emit event from component loop to main parent angular 5

我寫了下面的代碼,我循環組件來顯示子代

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>

在這里,我的問題是

  • 我能夠在parent.component.html中獲取發出的事件

  • 我無法從child.component.html獲取發出的事件
    parent.component.html

我正在錯誤的nodeClickedchild.component.ts定義

我在這做錯了什么? 我在這個問題上浪費了這么多時間。

謝謝您的幫助... :-)

在子組件中,您需要繼續將事件鏈接到父組件。 修改模板,以便在子事件發生時重新發出發射器。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM