2017-09-04 54 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)回答 –