2017-02-09 243 views
0

內相同類型的子組件的參考爲了得到孩子組件參考我們有選項 -我怎樣才能得到父組件

@ViewChild(ChildComponent) 
childComp: ChildComponent; 

我不知道如果我有相同的子組件的兩倍以上,怎麼可以在不同的變量中獲取所有相同類型的子組件。例如,在我的父模板中,我有 -

<div> 
    <child-selector></child-selector> 
    <child-selector></child-selector> 
</div> 

我怎樣才能獲得父組件內同一類型的子組件的引用?任何幫助將高度讚賞

回答

1

使用ViewChildren

@ViewChildren(ChildComponent) 
childComps: QueryList<ChildComponent>; 

*分別位於它的一個組成部分的模板內的兒童元素被稱爲*視*兒童。另一方面,在給定組件的主機 元素的開始標記和結束標記之間使用的**元素 被稱爲* content children **。

http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

+0

日Thnx的答案,當我試圖讓使用childComps.length它給未定義childComps的長度是多少?我如何迭代並獲取每個子選擇器引用? – deen

+0

你需要掛鉤到'AfterViewInit'生命週期,在這個事件觸發後,你可以遍歷你的列表。 https://angular.io/docs/ts/latest/api/core/index/AfterViewInit-class.html,https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html –