When does Angular2 ngAfterViewInit get called?

57,101

Solution 1

When does ngAfterViewInit get called?

ngAfterViewInit() should be called after a component's view, and its children's views, are created. I tested this, and found that children's ngAfterViewInit()s are called before the parent's ngAfterViewInit().

When you say "most of the HTML of my component has not even loaded", what do you mean by "loaded"? Is the HTML in the child component's template, or is it being loaded (or generated) by some other means?

How can I get my code to run after this directive has generated all of the html on which I need to operate?

It would help to see the directive code. If the directive somehow generates HTML that is not contained in Angular templates, then you may need to manually trigger an event (e.g., using an output property) to notify the parent when rendering has completed. Or you could use setTimeout() (but that would not be reliable).

I need some jQuery code to run after my Angular component view has initialized to transform number values into stars.

Where are you getting these number values from? If they are dynamically loaded from a server, you could trigger an event when the data arrives, and update the view at that point.

Also, why not write a component that takes a number as an input property and generates stars using NgFor?

Solution 2

I have been using ngAfterViewChecked when I depend on the DOM being ready.

import {Component, AfterViewChecked} from '@angular/core'; 

export class Spreadsheet implements AfterViewChecked{

   ngAfterViewChecked(){

   }
}
Share:
57,101
Gabe O'Leary
Author by

Gabe O'Leary

For fun I climb mountains and ski, and I'm here in an attempt to improve my web development skills.

Updated on July 30, 2022

Comments

  • Gabe O'Leary
    Gabe O'Leary almost 2 years

    I need some jQuery code to run after my Angular component view has initialized to transform number values into stars.

    I put the code in the ngAfterViewInit function, but it is not doing what I need it to. I set a break point in the function and I see that most of the HTML of my component has not even loaded by the time ngAfterViewInit function is called. The parts that have not loaded are generated using *ngFor directive.

    How can I get my code to run after this directive has generated all of the html on which I need to operate?