In this tutorial, we learn how to use Angular lifecycle hooks. The life cycle hooks are the methods that angular invokes on the directives and components as it creates, changes, and destroys them. Using lifecycle hooks we can fine-tune the behavior of our components during its creation, updating, and destruction.
When the angular application starts, it creates and renders the root component. It then creates and renders its Children & their children. It forms a tree of components.
Once Angular loads the components, it starts rendering the view. To do that, it needs to check the input properties, evaluate the data bindings & expressions, render the projected content, etc. Angular also removes the component from the DOM when it no longer needs it.
Angular lets us know when these events happen using lifecycle hooks
The Angular life cycle hooks are nothing but callback functions, which angular invokes when a specific event occurs during the component’s life cycle.
For example,
Here is the complete list of life cycle hooks, which angular invokes during the component life cycle. Angular invokes them when a specific event occurs.
Before diving into the lifecycle hooks, we need to understand the change detection cycle.
Change detection is the mechanism by which angular keeps the template in sync with the component
Consider the following code.
<div>Hello {{name}}</div>
Angular updates the DOM whenever the value of the name changes. And it does it instantly.
How does angular know when the value of the name changes? It does so by running a change detection cycle on every event that may result in a change. It runs on every input change, DOM event, and timer event like setTimeout(), setInterval(), HTTP requests, etc.
During the change detection cycle, angular checks every bound property in the template with that of the component class. If it detects any changes, it updates the DOM.
Angular raises the life cycle hooks during the critical stages of the change detection mechanism.
The life cycle of a component begins when Angular creates the component class. The first method that gets invoked is class Constructor.
Constructor is neither a life cycle hook nor is it specific to Angular. It is a Javascript feature. It is a method that is invoked when a class is created.
Angular makes use of a constructor to inject dependencies.
At this point, none of the component’s input properties are available. Neither its child components are constructed. Projected contents are also not available.
Hence there is little you can do with this method. And also, it is recommended not to use it
Once Angular instantiates the class, It kick-starts the first change detection cycle of the component.
The Angular invokes the ngOnChanges life cycle hook whenever any data-bound input property of the component or directive changes. Initializing the Input properties is the first task angular carries during the change detection cycle. And if it detects any change in property, then it raises the ngOnChanges hook. It does so during every change detection cycle.This hook is not raised if change detection does not detect any changes.
Input properties are those properties which we define using the @Input decorator. It is one of the ways by which a parent communicates with the child component.
In the following example, the child component declares the property message as the input property
@Input() message:string
The parent can send the data to the child using the property binding, as shown below.
<!--code box -->
<div class="example break">
<div class="codebox">
<div class="codebox-title">
<h4>Example</h4><a
href="../codelab.php?topic=javascript&file=sort-an-array-alphabetically"
target="_blank" class="try-btn" title="Try this code using online Editor">Try
this
code
<span>»</span></a>
</div>
<pre class="syntax-highlighter line-numbers language-javascript" style="tab-size:1;">
<code class="language-javascript">
<app-child [message]="message">
</app-child>
</code>
</pre>
</div>
</div>
<!--End of codebox-->
The change detector checks if the parent component changes such input properties of a component. If it is, then it raises the ngOnChanges hook.
We use this life cycle hook in the tutorial Passing data to the child component.
The change detector uses the === strict equality operator for detecting changes. Hence for objects, the hook is fired only if the references are changed. You can read more about it from Why ngOnChanges does not fire.
The Angular raises the ngOnInit hook after it creates the component and updates its input properties. It raises it after the ngOnChanges hook.
This hook is fired only once and immediately after its creation (during the first change detection).
This is a perfect place where you want to add any initialization logic for your component. Here you have access to every input property of the component. You can use them in HTTP get requests to get the data from the back-end server or run some initialization logic etc.
But note that none of the child components or projected content are available at this juncture. Hence any properties we decorate with @ViewChild, @ViewChildren, @ContentChild& @ContentChildren will not be available to use.
The Angular invokes the ngDoCheck hook event during every change detection cycle. This hook is invoked even if there is no change in any of the properties.
Angular invoke it after the ngOnChanges & ngOnInit hooks.
Use this hook to Implement a custom change detection whenever Angular fails to detect the changes made to Input properties. This hook is convenient when you opt for the Onpush change detection strategy.
The Angular ngOnChanges hook does not detect all the changes made to the input properties.
ngAfterContentInit Life cycle hook is called after the Component’s projected content has been fully initialized. Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook. This hook is also raised, even if there is no content to project.
The content here refers to the external content injected from the parent component via Content Projection.
The Angular Components can include the ng-content element, which acts as a placeholder for the content from the parent as shown below
<h2>Child Component</h2>
<ng-content></ng-content> <!-- placehodler for content from parent -->
The 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>
During the change detection cycle, Angular checks if the injected content has changed and updates the DOM.
This is a component-only hook.
ngAfterContentChecked Life cycle hook is called during every change detection cycle after Angular finishes checking of component’s projected content. 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 is very similar to the ngAfterContentInit hook. Both are called after the external content is initialized, checked & updated. The only difference is that ngAfterContentChecked is raised after every change detection cycle. While ngAfterContentInit during the first change detection cycle.
This is a component-only hook.
ngAfterViewInit hook is called after the Component’s View & all its child views are fully initialized. Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook.
The View here refers to the template of the current component and all its child components & directives.
This hook is called during the first change detection cycle, where angular initializes the view for the first time.
At this point, all the lifecycle hook methods & change detection of all child components & directives are processed & Component is entirely ready.
This is a component-only hook.
The Angular fires this hook after it checks & updates the component’s views and child views. This event is fired after the ngAfterViewInit and after that, during every change detection cycle.
This hook is very similar to the ngAfterViewInit hook. Both are called after all the child components & directives are initialized and updated. The only difference is that ngAfterViewChecked is raised during every change detection cycle. While ngAfterViewInit during the first change detection cycle.
This is a component-only hook.
This hook is called just before the Component/Directive instance is destroyed by Angular
You can Perform any cleanup logic for the Component here. This is where you would like to Unsubscribe Observables and detach event handlers to avoid memory leaks.
Let us build a simple component, which implements the ngOnInit hook
Create a Angular Project using Angular Cli. Open the app.component.ts
Import hook interfaces from the core module. The name of the Interface is hook name without ng. For example interface of the ngOnInit hook is OnInit.
import { Component,OnInit } from '@angular/core'
Next, define the AppComponent to implement OnInit interface
export class AppComponent implements OnInit {
The life cycle hook methods must use the same name as the hook.
ngOnInit() {
console.log("AppComponent:OnInit");
}
The complete code for the app.component.ts.
import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2>Life Cycle Hook</h2>` ,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor() {
console.log("AppComponent:Constructor");
}
ngOnInit() {
console.log("AppComponent:OnInit");
}
}
Now, run the code and open the developer console. you will see the following
AppComponent:Constructor
AppComponent:OnInit
Note that the constructor event is fired before the OnInit hook.
The Angular executes the hooks in the following order
On Component Creation
When the Component with Child Component is created
After The Component is Created
The OnChanges hook fires only if an input property is defined in the component and it changes. Otherwise, it will never fire.
app.component.ts
import { ChangeDetectionStrategy, Component, VERSION } from "@angular/core";
@Component,({
selector: "my-app",
changeDetection:ChangeDetectionStrategy.Default,
template: `
<h1>Angular Life Cycle Hooks</h1>
Reference :
<a
href="https://www.tektutorialshub.com/angular/angular-component-life-cycle-hooks/#create-the-hook-method"
>Angular Life Cycle Hooks</a
>
<h1>Root Component</h1>
<br />
<input
type="text"
name="message"
[(ngModel)]="message"
autocomplete="off"
/>
<br />
<input
type="text"
name="content"
[(ngModel)]="content"
autocomplete="off"
/>
<br />
hide child :
<input
type="checkbox"
name="hideChild"
[(ngModel)]="hideChild"
autocomplete="off"
/>
<br />
<br />
<app-child [message]="message" *ngIf="!hideChild">
<!-- Injected Content -->
<b> {{ content }} </b>
</app-child>
`
})
export class AppComponent {
name = "Angular " + VERSION.major;
message = "Hello";
content = "Hello";
hideChild=false;
constructor() {
console.log("AppComponent:Contructed");
}
ngOnChanges() {
console.log("AppComponent:ngOnChanges");
}
ngOnInit() {
console.log("AppComponent:ngOnInit");
}
ngDoCheck() {
console.log("AppComponent:DoCheck");
}
ngAfterContentInit() {
console.log("AppComponent:ngAfterContentInit");
}
ngAfterContentChecked() {
console.log("AppComponent:AfterContentChecked");
}
ngAfterViewInit() {
console.log("AppComponent:AfterViewInit");
}
ngAfterViewChecked() {
console.log("AppComponent:AfterViewChecked");
}
ngOnDestroy() {
console.log("AppComponent:ngOnDestroy");
}
}
child.component.ts
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { Customer } from './customer';
@Component,({
selector: 'app-child',
changeDetection:ChangeDetectionStrategy.Default,
template: `
<h2>child component</h2>
<br>
<!-- Data as a input -->
Message from Parent via @input {{message}}
<br><br>
<!-- Injected Content -->
Message from Parent via content injection
<ng-content></ng-content>
<br><br><br>
Code :
<input type="text" name="code" [(ngModel)]="customer.code" autocomplete="off">
<br><br>
Name:
<input type="text" name="name" [(ngModel)]="customer.name" autocomplete="off">
<app-grand-child [customer]="customer"></app-grand-child>
`
})
export class ChildComponent {
@Input() message:string
customer:Customer = new Customer()
constructor() {
console.log(" ChildComponent:Contructed");
}
ngOnChanges() {
console.log(" ChildComponent:ngOnChanges");
}
ngOnInit() {
console.log(" ChildComponent:ngOnInit");
}
ngDoCheck() {
console.log(" ChildComponent:DoCheck");
}
ngAfterContentInit() {
console.log(" ChildComponent:ngAfterContentInit");
}
ngAfterContentChecked() {
console.log(" ChildComponent:AfterContentChecked");
}
ngAfterViewInit() {
console.log(" ChildComponent:AfterViewInit");
}
ngAfterViewChecked() {
console.log(" ChildComponent:AfterViewChecked");
}
ngOnDestroy() {
console.log(" ChildComponent:ngOnDestroy");
}
}
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { Customer } from './customer';
@Component({
selector: 'app-grand-child',
changeDetection:ChangeDetectionStrategy.Default,
template: `
<h3>grand child component </h3>
<br>
Name {{customer.name}}
`,
})
export class GrandChildComponent {
@Input() customer:Customer
constructor() {
console.log(" GrandChildComponent:Contructed");
}
ngOnChanges() {
console.log(" GrandChildComponent:ngOnChanges");
}
ngOnInit() {
console.log(" GrandChildComponent:ngOnInit");
}
ngDoCheck() {
console.log(" GrandChildComponent:DoCheck");
}
ngAfterContentInit() {
console.log(" GrandChildComponent:ngAfterContentInit");
}
ngAfterContentChecked() {
console.log(" GrandChildComponent:AfterContentChecked");
}
ngAfterViewInit() {
console.log(" GrandChildComponent:AfterViewInit");
}
ngAfterViewChecked() {
console.log(" GrandChildComponent:AfterViewChecked");
}
ngOnDestroy() {
console.log(" GrandChildComponent:ngOnDestroy");
}
}
Run the code and check the console for the log messages
We learned about Component life cycle hooks in Angular. The Angular generates the following hooks OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked & OnDestroy. We then learned how to build an Application using the OnInit life cycle hook. Finally, we looked at the Order of execution of these life cycle hooks