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
- Input Event
- Browser Event
- SetTimeout
- SetInterval
- XHR Api request
- Promise
For OnPush Main change only trigger when
- Input property reference change
- 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
- Emission of an observable event subscribed with Async pipe
Benefits : -
- No Unnecessary Dirty Check in the Child Components
- 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.