我有一个 Angular 组件,它有另一个组件,也有另一个组件。因此,组件是嵌套的。
我想注意到所有子组件 View 何时完全呈现。 我尝试了所有的生命周期钩子(Hook),比如
ngAfterContentChecked
和
ngOnChanges
但是他们都没有被调用。是否可以识别渲染?
编辑:
我的 View 将动态更改。因此,我需要不仅仅在一开始就知道这一点。
我的组件看起来像:
父 View :
<child-1></child-1>
子 1 View :
<child-2><child-2>
最佳答案
您可以确定,当最深的和最后一个子组件中的 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
钩子(Hook)。有趣的是,这是反过来做的。所以你只需要在最父节点上监听就可以知道它什么时候完成检查。
心中有同一棵树:
@Component({
selector: 'parent'
})
export class ParentComponent implements AfterViewChecked {
ngAfterViewChecked(): void {
console.log('all done here');
}
}
另一方面,如果你想知道在事件被触发后, View 是否已经更新,你也可以只使用变化检测器,或 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()
使用任何方法。
关于angular - 注意 Angular 组件及其子组件何时被渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53301508/