Emit event through nested components in Angular2

前端 未结 3 823
猫巷女王i
猫巷女王i 2021-01-04 14:09

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

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 14:38

    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

提交回复
热议问题