2017-02-09 65 views
0

舉例來說,如果我有這樣的結構:Angular2:通過css類訪問多個子組件之一

<parent-component> 
    <child-a class="a"></child-a> 
    <child-a class="b selected"></child-a> 
    <child-b class="c"></child-b> 
    <child-b class="d"></child-b> 
    ... 
</parent-component> 

如何訪問ChildA的實例與類我爲父級「.selected」?

編輯: 在爲父級我有10個對象(在財產items)的列表,並在其模板我環比items陣列,併爲每一個項目創建ChildA或ChildB組件(ChildA或ChildB是否依賴於一些項目中的配置)。

然後通過點擊任何項目我將它標記爲'selected'(items中的相應對象存儲爲selectedItem)。後來,我需要訪問該組件,對應於selectedItem(並且有「.selected」類「)

+0

目前還不清楚你在問什麼。創建一個龐然大物,並澄清你的具體問題。 –

+0

不要以爲你可以通過它的課堂選擇一個孩子組件,而不需要查詢dom。你可以給它一個名字並使用'@ ContentChild'來選擇它。例如'' – rob

+0

@RomanC用更多的信息更新了問題。 – eagor

回答

3

在父用@ContentChild@ContentChildren

例如:。 在你的情況下使用: @ContentChildren(ChildComponentA) childs: QueryList<ChildComponentA>; 和u得到了所有孩子的 現在只是簡單的迭代

欲瞭解更多信息,請點擊這裏:https://angular.io/docs/ts/latest/api/core/index/ContentChildren-decorator.html


編輯: 您可以使用兒童ElementRef檢測所選類別中,在這裏,你就是一個例子:

plunkr here 正是這種做u想要做什麼?

+0

以及「.selected」類怎麼樣? – eagor

+1

最好的方法(現在和我)是添加屬性到child-N,isSelected,並檢查它當迭代trought組件查詢列表 – Daredzik

+0

@eagor我更新我的答案,我添加解決方案使用'ElementRef'它幫助你? – Daredzik