Angular: AfterViewInit() vs AfterContentInit()

This starts to make more sense if you’ve began some dynamic component loading or manual view creation in Angular.

OnInit is called once when the component’s @Inputs and @Outputs have been resolved.

AfterViewInit is called when the component’s view has been attached. Remember that Angular compiles all views to JS files, not html – the framework manages templates in code and has a rendering engine to interact with the DOM. In addition to actually rendering components, Angular needs to recursively build and manage child/parent relationships in regard to component bindings and their lifetime cycles. Child components will also need their bindings resolved and to go through the same rendering lifecycle as their parents. Simply put, at this hook @ViewChild and @ViewChildren will be resolved — child components will be fully initialized, and their properties will be available.

AfterContentInit is a little weirder. It’s called when the component’s child views and external content have been attached. This comes from content projection, normally into <ng-content> tags. It’s another step the renderer needs to take going down the tree, resolving all projected content before attaching it to the disjointed view. You really don’t need to worry about it if you’re not messing around with templates or <ng-content>. Here @ContentChild and @ContentChildren will be resolved.

As for the race condition you mentioned, there is no need to worry if you are using the right lifecycle hook for what’s needed — they’re just hooks called immediately after @Inputs, @ViewChildren, and @ContentChildren have been set on the component — race conditions for injected properties shouldn’t exist through the inversion of control to change detection (non-framework factors nonwithstanding) 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)