在同级组件中捕获事件 [英] Catch event in sibling component

查看:95
本文介绍了在同级组件中捕获事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用看起来像这样:

My app looks like this :

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

我想从my-toolbar交流到my-cube-container. 我正在从工具栏发送事件:

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);
  }
}

首先,我想在同级事件my-cube-container中捕获事件(请参见上面的应用程序结构).但是我读到,发出事件和捕获事件的关系仅保留给父母子女沟通. **是这样吗? **

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 ? **

因此,我尝试改为与父级进行通信(并在将来创建另一个eventEmitter,以便可以在目标组件my-cube-container中捕获该事件).但是,我仍然没有赶上这次活动.

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");
  }
}

我做错了什么?我需要在ngModul中进行更改吗?

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

推荐答案

您可以使用模板变量从模板中引用同级兄弟

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 >

这篇关于在同级组件中捕获事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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