【问题标题】:How to emit event from component loop to main parent angular 5如何从组件循环向主要父级角度5发出事件
【发布时间】:2018-11-03 19:12:24
【问题描述】:

我编写了以下代码,我在其中循环组件以显示子项

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

我收到错误,因为 nodeClicked 未在 child.component.ts

中定义

我在这里做错了什么?我在这个问题上浪费了很多时间。

感谢您的帮助... :-)

【问题讨论】:

  • 你的 child.component.html 中不需要这个 &lt;app-child [tree]="node.children" (nodeEmitter)="nodeClicked($event)"&gt;&lt;/app-child&gt;
  • 并且您收到该错误,因为 nodeClicked() 函数未在 child.component.ts 中定义
  • 那我怎样才能从子子子中获取发出的事件数据呢?能不能给个答案,没看懂。对不起!!!
  • @TeddySterne 在他的回答中已经提到过,您可以查看。谢谢

标签: javascript angular typescript components angular2-directives


【解决方案1】:

在子组件中,您需要继续将事件链接到父组件。修改您的模板,使发射器在子事件发生时重新发射。

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

【讨论】:

  • 非常感谢!!! @Teddy Sterne,您的回答有效。但是两次事件被发出。你知道,会有什么问题吗?再次感谢...
  • 模板事件绑定只是将事件向上传递到组件链,但所有事件都源自clickToEmit 方法。这是有道理的,因为ChildComponent 有多个嵌套实例。
猜你喜欢
  • 2017-10-18
  • 2020-10-06
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 2019-09-21
  • 2020-07-25
  • 2021-02-12
  • 2021-07-26
相关资源
最近更新 更多