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.
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.
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 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.
<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.
<h1>Parent Component</h1>
<app-child> This <b>content</b> is injected from parent</app-child>
View refer to the the template of the component.
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 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.
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.
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.
Once, we have reference to the DOM Element, we can use the renderor2 to manipulate its styles etc.
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.
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.
Now, now let use see above hooks using an example
child-component.ts
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');
}
}
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;
}
}
Now let us run this app and see what happens.
On the component creation, the hooks are fired in the following order.
Angular runs the change detection twice on application startup. Hence, the
Once the component is initialized, Angular do not fire the init hooks. Only the the checked hooks are invoked.
Angular initializes and checks the content first, before the components view & child views.
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 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.
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.
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.
ngAfterViewChecked() {
console.log('AppComponent==>AfterViewChecked');
this.message=this.viewChild.message;
}
Now add the following to the template of the app.component.ts
message from child {{message}}
and run the app.
There are two important points to note here.
Although the code looks fine, but this is what happens
Now, as you can see at the end of change detection h is not updated in DOM.
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.