At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

A Comprehensive Guide To Angular ChangeDetectionStrategy

  • By Manigandan
  • April 24, 2020
  • 800 Views

Change detection on components in Angular changes every time you make changes in the application like user event or data received from an API request. Angular ChangeDectionStrategy is primarily used to avoid performing all components every time something changes. Every change affects the amount of memory and leads to the slow performance of the application.
There are two types in Angular change detection strategy,

  1. Default
  2. OnPush

In this blog, you will learn how to use Change detection strategy default & OnPush. Firstly, Let’s discuss the “default”. Below example in the child component input using the default method.

1. Default

Users & childInput have to @Input() variable. It will get value from the parent component. Whenever changes are made to values, you should also check the input variable because of ChangeDetectionStrategy is available by default.
child.compinet.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
 selector: 'app-child',
 templateUrl: './child.component.html',
 styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {
 @Input() public users: any = [];
 @Input() public childInput: any;
 constructor() { }
 ngOnInit() {
 }}
<div *ngFor="let user of users">
 <p>user: {{user.name}} / Age: {{user.age}}</p>
</div>
<p>Test input : {{childInput}}</p>

App.component.ts

import { Component } from '@angular/core';
@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.less']
})
export class AppComponent {
 childData: any = 'angular-app';
 users = [{name: 'mani', age: 25}];
 changeInputData() {
   this.childData = 'angular-app' + Math.random();
   this.users.push({name: 'selva', age: 34});
 }
}

app.component.html

<button (click)="changeInputData()">change input</button>
<app-child [childInput]="childData" [users]="users"></app-child>

Parent component (app.component.ts). I have assigned users array value & childInputs value by default.
Initial output like below.
initial-defaultIf we click the “change input” button it changes the Users & childData variable value, then sample value changes to child component.
Angular change detection strategy

2. OnPush

ChangeDetectionStrategy Default checks every change in the parent component. Next, we will learn about OnPush. We can set the ChangeDetection of our component to ChangeDetectionStrategy – OnPush using the below lines of code.
child.component.ts

@Component({
 selector: 'app-child',
 templateUrl: './child.component.html',
 styleUrls: ['./child.component.less'],
 changeDetection: ChangeDetectionStrategy.OnPush
})

Users are array variables and will get the changes array values.
child.component.html

<div *ngFor="let user of users">
 <p>user: {{user.name}} / Age: {{user.age}}</p>
</div>

Parent component changes users’ values-based input changes click event.

<app-child
[users]="users"></app-child>

app.component.ts

users = [{name: 'mani', age: 35}];
 changeInputData() {
   this.users.push({name: 'selva', age: 34});
 }

As you might have noticed, now, users object array changed in the parent but not in the child component. The output as shown below.
onpush-initial

How to get the change value in a child?

Method 1 – Using ChangeDetectorRef

Whenever changes input variable and display changes using ChangeDetectorRef for a particular component using ngDoCheck methods.
Add the child component in the below code.

constructor(private cdRef: ChangeDetectorRef) { }
ngDoCheck(): void {
   //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
   //Add 'implements DoCheck' to the class.
   this.cdRef.markForCheck();
 }

Method 2 – Using Input Observable

Child input observable as shown below.

 _users  = [];
 @Input() users: Observable<any>;
 ngOnInit() {
   this.users.subscribe(users => {
     this._users = users;
     this.cdRef.markForCheck();
   });
 }

Parent component passing the behaviorSubjact values. So, when changes in the user data we can easily emit the observable.

users = [{name: 'mani', age: 35}];
 userObservable = new BehaviorSubject(this.users);
 changeInputData() {
   this.childData = Math.random();
   this.users.push({name: 'selva', age: 34});
   this.userObservable.next(this.users);
 }

I hope you find this Angular Tutorial Beneficial! Share with the folks if you think this might help.
Interested in learning more about Angular? Be well informed on updates by subscribing to the weekly newsletter. Fill the form and become a subscriber to access more exclusive updates on Angular and other development technologies.
Start your Angular Project with us! Talk to our technology experts today to build apps with a high compatible framework like Angular.

Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Manigandan

An ideal Full Stack Developer, having around 5+ years of experience in web development arena, expertise in AngularJS, Nodejs, PHP and also scoring 6 years of experience in Networking & Window servers. A perfect all-rounder has fondness to play diverse role. he always strives to match perfection and likely remains the best in whatever role he takes.