2017-04-24 54 views
1

我需要監聽來自一組選項卡組件的事件。這些選項卡會發出「onMinimized」,但我寧願在一行代碼中連接這些事件,而不是爲模板中的每個選項卡組件條目輸入(onMinimized)="hide"。我有一個ContentChildren數組,可以循環使用。如何在不通過模板連接的情況下收聽ContentChild事件?

我想要做同樣的事情到了如下父:

@ContentChildren(TabComponent) tabs: QueryList<TabComponent>; 

... 

ngAfterContentInit() { 
    this.tabs.map((t: TabComponent) => { 
    t.addEventListener("onMinimized", this.hide); 
    }); 
} 

hide() { 
    // hide tabs 
} 

的思考?

+0

IsMinimized是一個自定義事件發射器?因此,你可以在代碼中訂閱它。一個問題雖然 - 因爲選項卡是一個數組,是不是你循環通過該數組來創建TabComponents?或者你以不同的方式創建標籤? – snorkpete

+0

每個選項卡都在模板中定義(儘管它們可能在我想的數組中)。如何通過ContentChild參考創建ContentChild的角度「輸出」的事件偵聽器? – ktamlyn

+0

找到了這個,但它並不完全是我要找的。 http://stackoverflow.com/questions/37746058/what-is-the-best-way-to-detect-focus-event-in-contentchild-in-angular2 – ktamlyn

回答

0

經過一些試驗和錯誤後發現它。

ngAfterContentInit() { 
    this.tabs.map((t: TabComponent) => { 
     t.minimizeTab.subscribe(() => { this.hide(); }) 
    }); 
    } 

解決此問題的方法是考慮組件具有EventEmitter屬性(就像所有角度輸出一樣)。 EventEmitters是可觀察的,所以你可以簡單地訂閱事件流。

相關問題