Catch event in sibling component

久未见 提交于 2019-12-24 07:48:29

问题


My app looks like this :

<my-app>
  <my-toolbar></my-toolbar>
  <my-cube-container></my-cube-container >
</my-app>

I'd like to communicate from my-toolbar to my-cube-container. I'm sending an event from the toolbar :

@Component({
  selector: 'my-toolbar',
  template: `...
                    <i class="fa fa-search-minus ic" (click)='onZoom(-1)' aria-hidden="true"></i>
                    `,
})
export class ToolbarComponent {
@Output() zoomEvent: EventEmitter<number> = new EventEmitter();

  onZoom(value:number){
    console.log('event sent');
    this.zoomEvent.emit(value);
  }
}

And first I wanted to catch the event in the sibling which is my-cube-container (see app structure above). However I read that this relation of emitting event and catching those are solely reserved for parent children communication. ** Is that the case ? **

So I tried to communicate with the parent instead then (and create another eventEmitter in the future so I can catch the event in my target component my-cube-container). However I'm still not catching the event.

@Component({
  selector: 'my-app',
  template: `
              <my-toolbar></my-toolbar>
              <my-cube-container (zoomEvent)="onZoom($event)"></my-cube-container>

            `
})
export class AppComponent {
  onZoom(val){
    console.log("event catched");
  }
}

What I am doing wrong ? Do I need to change something in ngModul ?


回答1:


You can use template variables to reference siblings from within the template

<my-toolbar (zoomEvent)="container.onZoom($event)"></my-toolbar>
<my-cube-container #container></my-cube-container >


来源:https://stackoverflow.com/questions/39047451/catch-event-in-sibling-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!