2016-08-19 194 views
1

我的应用程序是这样的:捕捉事件

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

我想传达从my-toolbarmy-cube-container。 我从工具栏发送事件:

@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(见上面的应用程序结构)的兄弟。但是我读到,这种排放事件和捕捉这些关系仅仅是为父母子女沟通而保留的。 **是这样吗? **

所以我试图与父母沟通,然后(并在未来创建另一个事件发射器,以便我可以捕获目标组件my-cube-container中的事件)。不过,我仍然没有抓住这个事件。

@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中的内容吗?

回答

3

您可以使用模板变量从括号周围(zoomEvent)都应该意味着它是被追赶它自己的事件我-工具栏模板

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

中引用的兄弟姐妹。它看起来有点落后 - 或多余是一个更好的词 - 因为它是首先发布事件的组件。没有一种内置的方法可以直接从Component类中做到这一点? – Ced

+0

这不是'我的工具栏'来捕捉事件。它实际上是模板中具有此HTML的组件(通用父项)。您可以使用共享服务和可观察组件在非直接父 - 子组件之间进行通信,但对于这样一个简单的情况似乎过度。 –

+0

哦,是的,我的不好,谢谢 – Ced