How is changing the CD strategy from Default to onPush impact component? mostly asked interview Question

Anil Kumar
3 min readMay 8, 2021

--

Angular default Change Detection runs on every change it is also called as Check Always. So changing it for optimizing performance to OnPush (also called CheckOnce).

In Default Strategy CD triggers at following times

  1. Input Event
  2. Browser Event
  3. SetTimeout
  4. SetInterval
  5. XHR Api request
  6. Promise

For OnPush Main change only trigger when

  1. Input property reference change
  2. Browser Event triggered by component or it’s children.

If We need to trigger manually We have to use by changeDetectorRef methods

Detach: — Detach the view from CD tree.

MarkForcheck :- Mark view as change.

Reattach : — Reattach the View to CD tree

checkNoChange :- Check if there any changes

Detect Changes: — check the view and its children

If we don’t want use methods in OnPush then also some tweaks

  1. Emission of an observable event subscribed with Async pipe

Benefits : -

  1. No Unnecessary Dirty Check in the Child Components
  2. Faster Component Re-rendering

Some time there is a case for running Change Detection for Whole app then we can use ApplicationRef.tick() — which tells Angular to run change detection for the whole application.

Case of Object Mutability

Two Component Parent and Child

Parent

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

@Component({

selector: ‘myh-main’,

templateUrl: ‘./main.component.html’,

styleUrls: [‘./main.component.css’]

})

export class MainComponent implements OnInit {

constructor() { }

house = {

data:{ name:”Anil Kumar House”}

}

ngOnInit(): void {

}

}

Parent HTML :

<input type=”text” [(ngModel)]=”house.data.name”>

<myh-house [House]=”house”></myh-house>

Child Component

import { ChangeDetectionStrategy, Component, Input, OnInit } from ‘@angular/core’;

@Component({

selector: ‘myh-house’,

templateUrl: ‘./house.component.html’,

styleUrls: [‘./house.component.css’],

changeDetection:ChangeDetectionStrategy.Default

})

export class HouseComponent implements OnInit {

constructor() { }

@Input() House:any;

ngOnInit(): void {

}

}

Child HTML

{{House|json}}

If changing Input Values

Output :-

Changing CD to OnPush

@Component({

selector: ‘myh-house’,

templateUrl: ‘./house.component.html’,

styleUrls: [‘./house.component.css’],

changeDetection:ChangeDetectionStrategy.OnPush

})

Output :

Request :-

Suggestion and improvement are open! Please do comments.

--

--

Anil Kumar
Anil Kumar

Written by Anil Kumar

Software Engineer| Angular Advocate | Cyclist

No responses yet