Change detection is a key feature of Angular that keeps the UI updated with data. Angular automatically updates the view when component and child component data changes.

 

// app.component.ts
import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 counter: number = 0;

 incrementCounter() {
   this.counter++;
 }
}

<!-- app.component.html -->
<p>Counter: {{ counter }}</p>
<button (click)="incrementCounter()">Increment</button>

 

OnPush change detection

Angular's OnPush change detection mechanism optimises efficiency by only running change detection on components with changing inputs.
Immutable data or pure components benefit from it to avoid unnecessary checks and increase application speed.

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 changeDetection: ChangeDetectionStrategy.OnPush // Set OnPush strategy
})
export class AppComponent {
 // Component logic goes here
}


Related Question