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

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

问题描述

我的应用程序如下所示:

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天全站免登陆