Angular Change Detection
At a high level, change detection is the process of checking to see if something in your Angular application has changed, and then rendering the changes to the DOM so the user can see the updated application.
simply, Change Detection means updating the DOM whenever data is changed. Angular provides two strategies for Change Detection.
Change detection in Angular is implemented using Zone.js. Zone.js is a library that essentially patches many lower level browser APIs (like event handlers) so that the default functionality of the event occurs, as well as some custom Angular functionality. Zone.js patches all of the browser events (like click events, mouse events, etc), setTimeout and setInterval, and Ajax HTTP requests. If any of these events occur in your Angular app, Zone.js will cause change detection to run.
- In its default strategy, whenever any data is mutated or changed, Angular will run the change detector to update the DOM.
- In the onPush strategy, Angular will only run the change detector when a new reference is passed to @Input() data.
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-message',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<h2>
Hey {{person.firstname}} {{person.lastname}} !
</h2>
`
})
export class MessageComponent {
@Input() person;
}
In the above example, when ever the person object changes then change detection with update the DOm with updated value.
With onPush, Angular will only depend on the component’s inputs, events, markForCheck method, or the use of the async pipe in the template, to perform a change detection mechanism and update the view.
Situations to use OnPush:
- An input reference changes
- An event is emitted from the component or one of its children
- The developer explicitly marks the component as needing to be checked
- The async pipe is used in the view, or an Observable emits an event