![](/img/trans.png)
[英]Can't select component declared in a template for Angular 2 using @ViewChildren
[英]Can't get to @ViewChildren in parent component
我试图控制一个组件的子实例,并且不能出错。 我正在努力遵循这个问题的答案。
父组件Sequence
中包含的子组件SequenceStep
。 父级包含以下声明:
@ViewChildren(SequenceStep) steps: QueryList<SequenceStep>;
然后我想对孩子们做些事情:
ngAfterViewInit() {
this.steps.changes.subscribe(steps => {
console.log(steps);
});
}
我得到的错误是:
metadata_resolver.js:639未捕获的错误:由于未定义查询选择器,因此无法为“序列”的“步骤”属性构造查询。
而Sequence
和SequenceStep
组件的确在其@Component
装饰器中定义了它们的选择器(分别为sequence
和sequence-step
)。
我在这里做错了什么?
您是否尝试过在@ViewChildren arg中添加引号?
@ViewChildren('SequenceStep') steps: QueryList<SequenceStep>;
有几件事
如果您从外面传递孩子,他们不是孩子。 @ViewChild()
仅适用于直接添加到组件模板中的子级。
@ContentChildren()
处理被包含的内容:
@ContentChildren(TheChild) kids: QueryList<TheChild>;
this.kids.changes()
仅在初始化后通知更改。 因此,只需直接在ngAfterViewInit()
访问this.kids
,然后订阅即可获得有关以后更改的通知
ngAfterViewInit() { this.myKidsCount = this.kids.length; this.cdRef.detectChanges(); this.kids.changes.subscribe(kids => { this.myKidsCount = kids.length; }); }
当更改检测导致更改时,Angular不喜欢。 ngAfterViewInit()
由更改检测调用,这就是为什么this.myKidsCount = this.kids.length
导致异常的原因。
要变通,我在更改属性myKidsCount
后显式调用了更改检测:
constructor(private cdRef:ChangeDetectorRef){}
ngAfterViewInit() {
this.myKidsCount = this.kids.length;
this.cdRef.detectChanges();
}
此问题可能与SequenceStep的导入有关,请检查相关导入行的类名称。
@ViewChildren('SequenceStep') steps: QueryList<SequenceStep>;
为我工作。 Angular 4.XX Angular CLI 1.XX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.