简体   繁体   中英

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 :

<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. A hook to know when the view is actually fully loaded is really missing for 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.

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. 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. But I left it in, in case it helps another Ionic user or something...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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