简体   繁体   English

Angular 2组件完全加载后

[英]When an Angular 2 component has fully loaded

I cannot seem to find a hook by which I can know that a component that is made up of other child components has completely finished loading including data-binding and everything. 我似乎找不到一个钩子,通过它我可以知道由其他子组件组成的组件已完全完成加载,包括数据绑定和所有操作。 For example take the following template for ParentComponent : 例如,为ParentComponent使用以下模板:

<div>
    <child-one>
        {{textOne}}
    </child-one>
    <child-two>
        {{textTwo}}
    </child-two>
</div>

Any suggestion is highly appreciated. 任何建议都将受到高度赞赏。

It's wrong! 这是不对的! ngAfterViewInit is fired when the view is being initialized... Put a breakpoint into it and you will see. 初始化视图时会触发ngAfterViewInit。在其中插入一个断点,您将看到。 A hook to know when the view is actually fully loaded is really missing for Angular 2! Angular 2确实缺少了解视图实际何时完全加载的钩子! But as a workaround you could try something like that: 但是,作为一种解决方法,您可以尝试执行以下操作:

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()之后。

Building on Dimitri's answer, I've found that even after ngAfterViewInit is called, some elements were still not completely loaded, in my case I was after the scrollHeight of an element. 基于Dimitri的答案,我发现即使在调用ngAfterViewInit之后,某些元素仍然没有完全加载,就我而言,我是在元素的scrollHeight之后。

Using Ionic's platform.ready() and some timeout-testing, I noticed content finally being instantiated after about 60ms, so I increased it to 250ms just provide some wiggle-room. 使用Ionic的platform.ready()和一些超时测试,我发现内容在大约60ms之后最终被实例化,因此我将其增加到250ms,只是提供了一些摆动空间。 It's really not ideal but it's the last lifecycle hook to perform checks... but maybe it'll help someone? 确实不是很理想,但这是执行检查的最后一个生命周期钩子……但是也许会对某人有所帮助?

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);
    });
}

I know not everyone'll be using Ionic to have the Platform class available, it was only relevant to my use case as I was using ion-icons. 我知道并不是每个人都会使用Ionic来提供Platform类,这只与我的用例有关,因为我正在使用离子图标。 But I left it in, in case it helps another Ionic user or something... 但是我留了下来,以防其他离子用户帮忙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM