我正在开发一个棱角应用程序,它有一个父程序和一个子组件列表。父类使用两个api调用:
我想通过ViewChildren装饰器和ngAfterViewInit向每个子节点添加一个属性,所以我将以下内容放入父级中。
@ViewChildren(ChildrenComponent) children: QueryList<ChildrenComponent>;
ngAfterViewInit() {
this.children.changes.subscribe((children) => {
children.forEach((child) => {
child = 'Property!!'; // this string is dynamic in my app.
})
});
}订阅是在API调用A返回后触发的。这是预期的,因为一个新的子程序被添加到QueryList中。但是,在API调用B返回之后,它也会被调用。
根据关于ViewChildren装饰器的文档,只有在从QueryList中添加、移动和移除子程序时才会调用它。但是,API调用B只触及子级之外的div。为什么它会触发订阅?
我加入了一个SandBox来说明这种行为:https://codesandbox.io/s/angular-fll6r
ViewChildren文档:https://angular.io/api/core/ViewChildren
发布于 2019-08-21 02:15:47
你的apiARes将在1秒后被激活。在此期间内,父级中没有加载任何子级。为了演示起见,您将在检查时获得undefined。
ngOnInit() {
console.log(this.children) //undefined
// API call A
}一旦调用了API,就会加载子程序,这是子节点中的更改检测。您将得到查询结果。
setTimeout(() => {
this.apiARes = true;
console.log(this.children) // Query result
}, 1000);在子视图最初呈现后调用ngAfterViewInit()。这就是为什么@ViewChildren()依赖它。在呈现子成员之前,我们无法访问它们。
https://stackoverflow.com/questions/57583144
复制相似问题