2017-02-09 181 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 –