[英]When an Angular 2 component has fully loaded
我似乎找不到一个钩子,通过它我可以知道由其他子组件组成的组件已完全完成加载,包括数据绑定和所有操作。 例如,为ParentComponent
使用以下模板:
<div>
<child-one>
{{textOne}}
</child-one>
<child-two>
{{textTwo}}
</child-two>
</div>
任何建议都将受到高度赞赏。
这是不对的! 初始化视图时会触发ngAfterViewInit。在其中插入一个断点,您将看到。 Angular 2确实缺少了解视图实际何时完全加载的钩子! 但是,作为一种解决方法,您可以尝试执行以下操作:
ngAfterViewInit() {
console.log('View is being initialized');
console.log(this.el.nativeElement.offsetHeight);
setTimeout(() => {
console.log('View is fully loaded');
console.log(this.el.nativeElement.offsetHeight);
}, 0);
}
ngAfterViewInit() {}
或传递内容( <ng-content>
)时,将在ngAfterContentInit()
之后。
基于Dimitri的答案,我发现即使在调用ngAfterViewInit之后,某些元素仍然没有完全加载,就我而言,我是在元素的scrollHeight之后。
使用Ionic的platform.ready()
和一些超时测试,我发现内容在大约60ms之后最终被实例化,因此我将其增加到250ms,只是提供了一些摆动空间。 确实不是很理想,但这是执行检查的最后一个生命周期钩子……但是也许会对某人有所帮助?
constructor(public platform: Platform) {}
ngAfterViewInit() {
this.platform.ready().then(() => {
/* still returns 0 here */
console.log(this.el.nativeElement.scrollHeight);
setTimeout(() => {
/* returns x here */
console.log(this.el.nativeElement.scrollHeight);
}, 250);
});
}
我知道并不是每个人都会使用Ionic来提供Platform
类,这只与我的用例有关,因为我正在使用离子图标。 但是我留了下来,以防其他离子用户帮忙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.