2017-08-12 69 views
0

我正在開發一個小型項目,我正在編寫一個移動的第一個應用程序。 爲此,我打算在屏幕頂部有一個導航欄,在左側有一個菜單滑動屏幕。我希望這些組件在每個頁面/視圖上都可用。處理涉及多個組件的事件有哪些可能性?

我目前的架構是這樣的:

<app-component> 
-> <navbar-component> 
-> <sidemenu-component> 
-> <router-outlet><!-- The different pages will be placed here !--></router-outlet> 

現在我希望能夠在navbar-component點擊一個按鈕,打開sidemenu-component

爲此,我需要在sidemenu註冊點擊事件或在導航欄中觸發sidemenu的其他組件的參考。

我最初的想法是使用@Input()@Output()屬性來傳遞組件的引用。

//app-component.html 
<navbar-component [parentComponent]="referenceToAppComponent" (instance)="navbarComponent"></navbar-component> 
<sidemenu-component [parentComponent]="referenceToAppComponent" (instance)="sidemenuComponent"></sidemenu-component> 
+3

不,你不需要組件的引用。只需在這兩個組件之間共享一個服務,並從這個共享服務中發出事件(使用可觀察事件)。 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service –

+0

你可能會考慮使用路由器來做到這一點。您可以使用命名的插座,並將菜單的開頭顯示爲路線本身,並通過導航欄導航到路線 –

回答

0

輸入,輸出的API可當你有父/子組件使用。所以使用Input,父母將數據發送給孩子,並使用Output,孩子可以發送數據給父母

現在在這裏,似乎你處理兄弟組件(沒有父/子方案)。對於這種類型的兄弟情況,可以使用共享服務
但請確保使用SINGLEET SHARED SERVICE
Singleton共享服務將在整個應用程序中共享一個服務實例,因此您可以在兄弟組件之間進行通信。

更多細節:https://angular.io/guide/component-interaction