通过Angular2中的嵌套组件发出事件 [英] Emit event through nested components in Angular2

查看:89
本文介绍了通过Angular2中的嵌套组件发出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用Output()装饰器从子组件中发出事件,以便父组件可以捕获该事件.我需要捕获任何子组件发出的事件,这不一定是给定组件的直接子组件.

One can use Output() decorator to emit the event from the child component so that the parent component can catch it. What I need is to catch an event emitted by any child component, which is not necessarily a direct child of a given component.

ComponentTwo是发出事件的组件.如果应用程序具有以下结构:App -> ComponentTwo,那么我们可以轻松捕获ComponentTwo发出的事件.但是,如果考虑使用App -> ComponentOne -> ComponentTwo之类的结构,那么我们将无法直接捕获发射器.

Let ComponentTwo be a component which emits the event. If the app has the following structure: App -> ComponentTwo, then we can easily catch the event emitted by ComponentTwo. But if we consider structure like App -> ComponentOne -> ComponentTwo, then we can't catch the emitter directly.

这是说明问题的 plunker .

那么有没有一种方法可以将传播事件分类到所有父组件?谢谢.

So is there a way to sort of propagate event to all parent components? Thanks.

推荐答案

不支持对此类事件进行冒泡.您需要手动捕获它们并将其发送给父级.

There is no support of bubbling for such events. You need to manually catch them and emit to the parent.

另一种方法是为该组件树利用共享服务,并在其中使用可观察的/主题.

Another approach would be to leverage a shared service for this tree of components and use an observable / subject in it.

通过这种方式,所有组件都可以订阅它,即使在子子孩子中也可以得到事件通知.

This way all components can subscribe on it to be notified of events even within sub sub children.

constructor(private service: SharedService) {
  this.service.notifier$.subscribe(
    data => {
      (...)
    });
}

事件将通过以下方式触发:

The event will be triggered this way:

constructor(private service: SharedService) {
}

notify() {
  this.service.notifier$.next('some data');
}

有关更多详细信息,请参见此链接:

See this link for more details:

这篇关于通过Angular2中的嵌套组件发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆