Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit event through nested components in Angular2

Tags:

angular

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.

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.

Here is a plunker that illustrates the problem.

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

like image 406
nakajuice Avatar asked May 06 '16 13:05

nakajuice


1 Answers

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:

  • https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
like image 112
Thierry Templier Avatar answered Oct 17 '22 04:10

Thierry Templier