2017-09-04 49 views
0

我一直在玩角组件,并且出现了我有多个嵌套组件的情况,比如4个级别,比如RootComponent-> GranParentComponent-> ParentComponent-> ChildComponent。我需要在RootComponent中使用来自ChildComponent的数据调用一些服务,当我对ChildComponent进行更改时。我已经通过组件创建了EventEmiters并且它可以工作,但问题是我可以在不通过组件的情况下通过RootComponent进行通信。 在此先感谢。角度检测通过嵌套组件改变

回答

1

Angular不支持事件冒泡。如果事件冒泡对您的应用程序很重要,请勿使用EventEmitter;改为使用本地DOM事件。在你ChildComponent做这样的事情:

constructor(element: ElementRef){} 
... 
this.element.nativeElement 
.dispatchEvent(new CustomEvent('myCustomEvent', {foo:bar})); 

在你RootComponent:

<div (myCustomEvent)= doSomething($event)> 
    <GrandParentComponent ></GrandParentComponent> 
</div> 
+0

这是正常击发ChildComponent事件和RootComponent执行某些功能,但如何传递对象与数据。我创建了一个示例代码来说明https://stackblitz.com/edit/angular-heachx?file=app%2Fparent.component.ts –

+1

您需要使用CustomEvent的detail属性。更新您的示例https://stackblitz.com/edit/angular-56wcbh?file=app%2Fapp.component.ts 打开浏览器控制台查看应用程序组件的输出。 –

+0

工作正常(+1)回答 –