您可以确定,当最深和最后一个子组件中的ngAfterViewInit 被调用时,所有的祖先也会被渲染。
这基本上意味着,如果你有这样的结构:
<parent>
<child-1>
<child-2></child-2>
<child-3></child-3>
</child-1>
</parent>
您可以确定当child-3 调用ngAfterViewInit 时,树中的所有内容都会被渲染:
@Component({
selector: 'child-3'
})
export class Child3Component implements AfterViewInit {
ngAfterViewInit(): void {
console.log('all done here');
}
}
如果你想知道什么时候通过树处理更新以及模板在一个周期后更新,你需要使用ngAfterViewChecked钩子。有趣的事实是,这是相反的。所以你只需要在最父节点上监听就可以知道它什么时候完成了检查。
记住同一棵树:
@Component({
selector: 'parent'
})
export class ParentComponent implements AfterViewChecked {
ngAfterViewChecked(): void {
console.log('all done here');
}
}
另一方面,如果你想知道一个事件被触发后,视图是否被更新,你也可以只使用变化检测器,或者 applicationRef,或者一个 setTimeout:
如果这部分代码在你的组件中
(不应该!不要在组件内部直接使用http!)
this.http.get(url).subscribe((data) => {
this.data = data;
// method 1:
setTimeout(() => {
// view is rendered here
});
// method 2:
this.changeDetectorRef.detectChanges();
// view is rendered here
// method 3:
this.applicationRef.tick();
// view is rendered here
});
但请注意,如果您的组件(或任何父组件)将 changeDetection 设置为 OnPush,您首先必须使用任何方法设置:this.changeDetectorRef.markForCheck()。