AfterViewInit, AfterContentInit, AfterViewChecked & AfterContentChecked are the life cycle hooks. Angular raise them during the lifecycle of a Component. In this tutorial, we will learn what are they and when Angular invokes them. We also learn the difference between the AfterViewInit Vs AfterContentInit Vs AfterViewChecked & AfterContentChecked.
Table of Contents
Lifecycle hooks recap
The life of a component (or directive) starts, when angular instantiates the component.
Instantiation starts with invoking the component’s constructor and injecting the services via dependency injection.
Once the Angular instantiates the component, it starts the change detection cycle for the component. It checks & updates any data-bound input property of the component & Initializes the component. It then raises the following life cycle hooks.
Onchanges, if Angular detects any changes to the Input property. It runs every time angular detects an input change.
OnInit, which tells us that the component is ready. This hook gives us a chance to run any initialization logic, updates a few properties, etc. This hook runs only once.
DoCheck which allows us to run custom change detection because change detection may overlook some of the changes. This hook runs during every change detection cycle.
After this angular invokes four more hooks. They are AfterContentInit
, AfterContentChecked
, AfterViewInit
& AfterViewChecked
. We will look at them in detail.
Finally, when we remove the component, Angular invokes the ngOnDestroy hook and then destroys the component.
Content Vs View
Before diving into these hooks, we need to know the difference between Content & View. The hooks AfterConentInit
& AfterContentChecked
deals with the Content, While AfterViewInit
, AfterViewChecked
deals with the View.
Content
Content refers to the external content injected into this component using the Content Projection.
Content projection
is a way to pass the HTML content from the parent component to the child component. The child component will display the template in a designated spot. We use the ng-content
element to create a spot in the template of the child component as shown below.
1 2 3 4 | <h2>Child Component</h2> <ng-content></ng-content> <!-- place hodler for content from parent --> |
Parent injects the content between the opening & closing element. Angular passes this content to the child component.
1 2 3 4 5 | <h1>Parent Component</h1> <app-child> This <b>content</b> is injected from parent</app-child> |
View
View refer to the the template of the component.
AfterContentInit
The AfterContentInit
is the Life cycle hook that angular calls after the Component’s content has been fully initialized and injected into Components View.
Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook.
Angular calls this hook even if there is no projected content in the component
This hook fires after the ngDoCheck
hook.
Fires only once, during the first change detection cycle, immediately after the creation of the component.
AfterContentChecked
AfterContentChecked
is the life cycle hook, that angular calls during every change detection cycle after Angular completes the checking of the content for changes.
Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook.
This hook fires after the ngDoCheck
& AfterContentInit
.
AfterViewInit
A lifecycle hook that Angular calls during the change detection after it completes initialization of component’s view and its child views.
Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.
Use this hook to handle any additional initialization tasks.
Fires only once, during the first change detection cycle, immediately after the creation of the component.
AfterViewChecked
A lifecycle hook that Angular calls after the change detector completes the checking of a component’s view and child views for changes.
Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.
Init Vs Checked
Init Hooks
Angular fires the AfterContentInit
& AfterViewInit
hooks, when the content or view is initialized for the first time. That happens during the first change detection cycle, which angular invokes immediately after the instantiation of the component.
Checked Hooks
Angular fires the AfterContentChecked
& AfterViewChecked
hooks, where Angular checks if the the content or view has changed. i.e previously rendered content or view is same as the current content or view.
Example
Now, now let use see above hooks using an example
child-component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import { Component } from "@angular/core"; @Component({ selector: "app-child", template: ` <div style="border:solid; border-width:1px;"> <h2>Child Component</h2> message : <input [(ngModel)]="message"> <p> Injected Content Below</p> <ng-content></ng-content> </div> `, }) export class ChildComponent { message = "" ngOnChanges() { console.log(' ChildComponent==>ngOnChanges'); } ngOnInit() { console.log(' ChildComponent==>ngOnInit'); } ngDoCheck() { console.log(' ChildComponent==>ngDoCheck'); } ngAfterContentInit() { console.log(' ChildComponent==>ngAfterContentInit'); } ngAfterContentChecked() { console.log(' ChildComponent==>ngAfterContentChecked'); } ngAfterViewInit() { console.log(' ChildComponent==>AfterViewInit'); } ngAfterViewChecked() { console.log(' ChildComponent==>AfterViewChecked'); } } |
- We have a input FORM element, which is bound to
message
property of the component using ngModel <ng-content></ng-content>
is a place holder for the injected content from the parent.- The code
ex: console.log(' ChildComponent==>ngOnChanges');
in the component logs to console, whenever change detection invokes the hook;
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import { Component, ViewChild } from "@angular/core"; import { ChildComponent } from "./child-component"; @Component({ selector: "my-app", template: ` AfterConentInit, AfterContentChecked, AfterViewInit, AfterViewChecked <app-child> <b>Injected</b> content from the <i>Parent</i> </app-child> `, }) export class AppComponent { message=""; @ViewChild(ChildComponent) viewChild: ChildComponent; ngOnChanges() { console.log('AppComponent==>ngOnChanges'); } ngOnInit() { console.log('AppComponent==>ngOnInit'); } ngDoCheck() { console.log('AppComponent==>ngDoCheck'); } ngAfterContentInit() { console.log('AppComponent==>ngAfterContentInit'); } ngAfterContentChecked() { console.log('AppComponent==>ngAfterContentChecked'); } ngAfterViewInit() { console.log('AppComponent==>AfterViewInit'); } ngAfterViewChecked() { console.log('AppComponent==>AfterViewChecked'); this.message=this.viewChild.message; } } |
- We are injecting the content to
<app-child>
by placing the content<b>Injected</b> content from the <i>Parent</i>
within the element tag. - Using
ViewChild
query to update the reference to the child component in the propertyChildComponent
this.message=this.viewChild.message;
updates themessage
property of this component with that ofChildComponent
Now let us run this app and see what happens.
On Component Creation
On the component creation, the hooks are fired in the following order.
Angular runs the change detection twice on application startup. Hence, the
On Component Running
Once the component is initialized, Angular do not fire the init
hooks. Only the the checked hooks are invoked.
- DoCheck
- AfterContentChecked
- AfterViewChecked
Content is first
Angular initializes and checks the content first, before the components view & child views.
AfterViewInit & AfterViewChecked fires after child components are ready
After content, angular initializes the components view. It also initializes the child views & runs thier change detection. Hence, by the time we receive the hooks AfterViewInit
& AfterViewChecked
, the current component & all its children are ready to render.
Init Hook fires only once
Init hooks fires only once, during the first change detection cycle, which angular fires immediately after the creation of the component. This makes it best place to run some custom initialization logic. Use the AfertContentInit
for content related initialization & AfterViewInit
for view related initializations.
Avoid using Checked Hooks
Checked hooks runs on every change detection cycle. For example when you just click on the input element and move away.
Hence it is better to avoid using these hooks. If you choose to implement these hooks then ensure that your code is extremely lightweight otherwise it may slow down the application.
Do not modify bindings in Checked Hooks
Open the ngAfterViewChecked
method of the app.component.ts
. here, we assign value of the viewChild.message
to the message
variable of parent component. Code does not raise any errors.
1 2 3 4 5 6 | ngAfterViewChecked() { console.log('AppComponent==>AfterViewChecked'); this.message=this.viewChild.message; } |
Now add the following to the template of the app.component.ts
1 2 3 | message from child {{message}} |
and run the app.
There are two important points to note here.
- The
{{message}}
in theapp.component.ts
waits a tick before updating ExpressionChangedAfterItHasBeenCheckedError
Although the code looks fine, but this is what happens
- Initially the value of
message
is empty - We enter
h
in input element. This starts a change detection cycle. - It checks the value of
message
variable. Its value is empty. Hence updates the DOM with empty string. - Angular fires the
AfterViewChecked
hook - We update the
message
variable toh
. - Angular runs another check to see if all the bindings values are correct. If detects
message
value is nowh
is different from when it checked it in the step 3. It raises theExpressionChangedAfterItHasBeenCheckedError
- Change detection cycle ends.
Now, as you can see at the end of change detection h
is not updated in DOM.
- We, type
e
in input element. - A change detection cycle starts
- It checks the value of
message
variable. Its value ish
. Hence Angular updates the DOM withh
. - Angular fires the
AfterViewChecked
hook - We update the
message
variable tohe
. - Angular runs another check to see if all the bindings values are correct. If detects
message
value is nowh
is different from when it checked it in the step 3. It raises theExpressionChangedAfterItHasBeenCheckedError
. - Change detection cycle ends.
The step 6 only happens only in development mode. Angular only checks the bindings, but does not update the DOM if it detects any changes. It only raises the error.
great article
mind-blowing information
Nice article