Performance: Why change detection matters
Change detection impacts how fast the page updates after user actions or data changes, affecting interaction responsiveness and visual stability.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-root', changeDetection: ChangeDetectionStrategy.OnPush, template: `<div>{{ counter }}</div><button (click)="increment()">Increment</button>` }) export class AppComponent { counter = 0; increment() { this.counter++; } }
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<div>{{ counter }}</div><button (click)="increment()">Increment</button>` }) export class AppComponent { counter = 0; increment() { this.counter++; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default Change Detection | Many unnecessary checks | Multiple reflows per event | High paint cost due to frequent updates | [X] Bad |
| OnPush Change Detection | Checks only when needed | Single or minimal reflows | Lower paint cost with fewer updates | [OK] Good |
export function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return `Count: ${count}`;
}increment() is called but Angular's change detection does not run?import { ChangeDetectorRef } from '@angular/core';
@Component({ selector: 'app-test', template: `{{value}}
` })
export class TestComponent {
value = 0;
constructor(private cdr: ChangeDetectorRef) {}
update() {
this.value = 1;
// Missing change detection trigger here
}
}value not update after calling update()?Pass the test and this pattern moves unknown