typescript 如何冒泡 angular2 自定义事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37010507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:27:44  来源:igfitidea点击:

How to bubble up angular2 custom event

typescriptangular

提问by Mario G.

Parent template:

父模板:

<ul>
   <tree-item [model]="tree" (addChild)="addChild($event)"></tree-item>
</ul>

Tree item template:

树项模板:

<li>
  <div>{{model.name}}
    <span [hidden]="!isFolder" (click)="addChild.emit(model)">Add Child</span>
  </div>
  <ul *ngFor="let m of model.children">
    <tree-item [model]="m"></tree-item>
  </ul>
</li>

For above example, parent receives addChild event only from the root tree-item (immediate child). Is it possible to bubble up addChild event from any tree-item? I am using angular 2.0.0-rc.0.

对于上面的示例,父项仅从根树项(直接子项)接收 addChild 事件。是否可以从任何树项中冒出 addChild 事件?我正在使用 angular 2.0.0-rc.0。

回答by Günter Z?chbauer

Events from EventEmitterdon't support bubbling.

来自EventEmitter不支持冒泡的事件。

You can either use element.dispatchEvent()to fire a DOM event that bubbles, or use a shared service like a message bus.

您可以使用element.dispatchEvent()来触发冒泡的 DOM 事件,也可以使用消息总线等共享服务。

See also https://angular.io/docs/ts/latest/cookbook/component-communication.html

另见https://angular.io/docs/ts/latest/cookbook/component-communication.html

回答by Derek

I came here looking for a solution, and I figured out one on my own. On your tree-item, you can add an event handler like so:

我来到这里寻找解决方案,我自己想出了一个解决方案。在您的 上tree-item,您可以添加一个事件处理程序,如下所示:

<li>
  <div>{{model.name}}
    <span [hidden]="!isFolder" (click)="addChild.emit(model)">Add Child</span>
  </div>
  <ul *ngFor="let m of model.children">
    <tree-item [model]="m" (yourEventEmitter)="handleEventBubble($event)"></tree-item>
  </ul>
</li>

and in your component.ts:

并在您的 component.ts 中:

handleEventBubble(event): void {
  this.yourEventEmitter.emit(event);
}

This will cause the event to emit on the parent element, which passes up the chain all the way up to the root element. You can even define custom bubbling logic by transforming the event before re-emitting it.

这将导致事件在父元素上发出,父元素一直向上传递到根元素。您甚至可以通过在重新发出事件之前转换事件来定义自定义冒泡逻辑。