Sitemap
Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Angular Lifecycle

--

Angular is a client-side typescript-based JavaScript framework that is used to develop web-based and mobile applications. The following link includes a basic introduction to Angular.

Press enter or click to view image in full size

In angular components, we can find eight different phases in their lifecycle. It is always checked whenever the components get loaded during the development of the application. All the events that occurred in the component’s life are called lifecycle hooks in Angular. These hooks can be called at any time by using their own methods. Let’s discuss these eight lifecycle hooks.

01. ngOnInit(): After creating the constructor of the component, we can implement this method as a start-up method. This method will contain all the component-load-related operations. For example, let’s assume component A has a user table. So we need to load user data and bind that data into the HTML table when the component is loaded. Those operations are done inside the ngOnInit() method. The following is example code for the ngOnInit lifecycle hook.

import {Component, OnInit} from '@angular/core';
import {UserService} from "../service/user.service";
import {UserDto} from "../dto/userDto";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

constructor(private userService: UserService) {}

ngOnInit(): void {
const data = new UserDto('sachith.vidu@yahoo.com', 'Sachith Ariyathilaka', 'sachith.vidu@yahoo.com', '12345');
this.userService.saveUser(data).subscribe(response => {
console.log(response);
}, (error: any) => {
console.log(error);
});
}
}

02. ngOnChanges(): This method is called whenever the component’s bound input is changed from the parent component. We can use the @Input() decorator to detect the change in the parent component. We must call this method after the ngOnInit() method. Let’s use the following example to explain this lifecycle hook.

import { Component, OnInit, Input, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-child',
template: `
<a (click)="changeFromChild()">Change from child</a>
<br/>
{{parentData}}
`
})
export class ChildComponent implements OnInit {

@Input() parentData: any;

constructor() {}

ngOnInit() {
console.log("Component data loaded")
}

changeFromChild(){
this.parentData -= 1;
}

ngOnChanges() {
console.log("Parent data changes detected")
}
}
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-parent',
template: `
<a (click)="changeFromParent()">Change from parent</a>
<br/>
<app-child [parentData]=data></app-child>
`
})
export class ParentComponent implements OnInit {

data = 0;

constructor() {}

ngOnInit() {}

changeFromParent(){
this.data += 1;
}
}

According to this example, every time parent data is changed, ngOnChanges() is captured in the child components with updated data.

Get Sachith Ariyathilaka’s stories in your inbox

Join Medium for free to get updates from this writer.

03. ngDoCheck(): This method is called whenever change detection is run. We need to implement this method after the ngOnInit() and ngOnChanges() methods. This hook is also very similar to ngOnChanges(). For example, let’s assume parent data is not changing after a button click. ngOnChanges() does not trigger, but ngDoCheck() will trigger. Following are examples of codes for this hook.

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

@Component({
selector: 'app-parent',
template: `<a (click)="updateUser()">Update</a><br/>
<app-child [user]="user"></app-child>`
})
export class ParentComponent implements OnInit {

user = { name:"Alex" }

constructor() {}

ngOnInit() {}

updateUser(){
this.user.name = "ted"
}
}
import { Component, OnInit, Input, ChangeDetectionStrategy, DoCheck, OnChanges } from '@angular/core';

@Component({
selector: 'app-child',
template: `Here is the user name: {{ user.name }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {

@Input() user;

constructor() {}

ngOnInit() {}

ngOnChanges(){
console.log("Parent data changes detected")
}

ngDoCheck(){
console.log("All click events detected")
}
}

04. ngAfterContentInit(): This lifecycle hook runs once after the first ngDoCheck() method. We will use this hook to call it after all the content has been initialized. This should be implemented after ngOnInit() and ngDoCheck(). Following are some example code blocks for the ngAfterContentInit() lifecycle hook.

import { Component, OnInit, AfterContentInit, DoCheck } from '@angular/core';

@Component({
selector: 'app-root',
template: `<a (click)="clickMe()">Click me</a>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

constructor() { }

ngOnInit() {
console.log("app component init")
}

ngDoCheck(){
console.log("Do Check Called")
}

ngAfterContentInit(){
console.log("After Content Init");
}

clickMe(){
console.log("link clicked")
}

}

05. ngAfterContentChecked(): This lifecycle hook is called after the ngAfterContentInit() method. But this method will be called after every subsequent call to ngDoCheck(). This method is used to call the lifecycle event hook immediately after ngDoCheck(). Following are some example code blocks for the ngAfterContentChecked() lifecycle hook.

import { Component, OnInit,  DoCheck, AfterContentChecked } from '@angular/core';

@Component({
selector: 'app-root',
template: `<a (click)="clickMe()">Click me</a>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

constructor() {}

ngOnInit() {
console.log("app component init")
}

ngDoCheck(){
console.log("do check")
}

ngAfterContentChecked(){
console.log("after content checked")
}

clickMe(){
console.log("link clicked")
}

}

06. ngAfterViewInit(): ngAfterViewInit() is useful when you want to call a lifecycle hook after all child components have been initialized and checked. This will be called once after ngDoCheck() is triggered. This can be called after ngOnInit() and ngDoCheck(). Following are some example code blocks for the ngAfterViewInit() lifecycle hook.

import { Component, OnInit, DoCheck, AfterViewInit } from '@angular/core';

@Component({
selector: 'app-root',
template: `<a (click)="clickMe()">Click me</a>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

constructor() {}

ngOnInit() {
console.log("app component init")
}

ngDoCheck(){
console.log("do check")
}

ngAfterViewInit(){
console.log("after view init")
}

clickMe(){
console.log("link clicked")
}
}

07. ngAfterViewChecked(): ngAfterViewChecked() is useful when you want to call a lifecycle hook after all child components have been initialized and checked. This is called every subsequent of ngAfterContentChecked(). This can be called after ngOnInit() and ngDoCheck(). Following are some example code blocks for the ngAfterViewChecked() lifecycle hook.

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

@Component({
selector: 'app-root',
template: `<a (click)="clickMe()">Click me</a>`,
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

constructor() {}

ngOnInit() {
console.log("app component init")
}

ngDoCheck(){
console.log("do check")
}

ngAfterViewChecked(){
console.log("after view checked")
}

clickMe(){
console.log("link clicked")
}

}

08. ngOnDestroy(): This lifecycle hook is used to implement customized behavior when a component is destroyed. It is mainly used to unsubscribe from observables or perform any other clean-up operation once a component has been destroyed. Following are some example code blocks for the ngOnDestroy() lifecycle hook.

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

@Component({
selector: 'app-root',
template: ['./sample.component.html'],
styleUrls: ['./sample.component.css']
})
export class AppComponent implements OnInit {

constructor() {}

ngOnInit() {
console.log("app component init")
}

ngOnDestroy(){
console.log("destroying app component...")
}

}

As per the above clarification, we can summarize the lifecycle hooks as the total states of an angular component.

--

--

Towards Dev
Towards Dev

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.