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

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

For OnPush Main change only trigger when

  1. Input property reference change

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

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.

--

--

Software Engineer | Bharat Swabhiman Patanjali Social Activist | Speaker | Motivator | Yoga Trainer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
ACHARYA ANIL SURYAVANSHI

Software Engineer | Bharat Swabhiman Patanjali Social Activist | Speaker | Motivator | Yoga Trainer