Output event via nested components in Angular2

You can use the Output() decorator to emit an event from a child component so that the parent component can catch it. I need to catch the event emitted by any child component that is not necessarily the direct descendant of this component.

Let ComponentTwo be the component that emits the event. If the application has the following structure: App -> ComponentTwo , we can easily catch the event emitted by ComponentTwo . But if we look at a structure like App -> ComponentOne -> ComponentTwo , we cannot catch the emitter directly.

Here is a plunker that illustrates the problem.

So, is there a way to sort the propagation event in all parent components? Thanks.

+4
angular
source share
1 answer

There is no bubble support for such events. You need to manually catch them and release the parent.

Another approach would be to use a common service for this component tree and use the observable / subject in it.

Thus, all components can subscribe to it to receive event notifications even in subsidiary child units.

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

The event will be triggered as follows:

 constructor(private service: SharedService) { } notify() { this.service.notifier$.next('some data'); } 

See this link for more details:

+12
source share

All Articles