Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Change Detection is Angular mechanism that monitors data changes and updates template (DOM) if needed.
When something changes in application — Angular triggers change detection process and compares component values with what's already rendered to determine if DOM needs re-rendering.
{{ value }}, [property], (event)) for changes.Angular uses zone.js library to automatically "capture" events causing changes:
| Change source | Example |
|---|---|
| DOM events | click, input, change, etc. |
| Timers | setTimeout, setInterval |
| HTTP requests | HttpClient |
| Promise and async/await | fetch().then(...), await |
| Internal changes | this.value = ... |
@Component({
selector: 'app-example',
template: `<p>{{ counter }}</p> <button (click)="increment()">+</button>`
})
export class ExampleComponent {
counter = 0;
increment() {
this.counter++;
}
}
Angular automatically tracks counter change after button click and updates DOM.
Angular supports two change detection strategies:
| Strategy | Description |
|---|---|
Default | Angular checks all components on any change |
OnPush | Angular checks component only when Input parameters change or events occur |
Using OnPush:
@Component({
selector: 'app-optimized',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user.name }}</p>`
})
export class OptimizedComponent {
@Input() user!: { name: string };
}
This reduces number of checks, improving performance, especially in large applications.
Angular uses reference comparison (shallow reference check):
this.user.name = "John"; // doesn't trigger OnPush!
this.user = { name: "John" }; // triggers, because new reference
To update component with OnPush strategy — need to create new object.
ChangeDetectionStrategy.OnPush everywhere possible.trackBy in *ngFor to avoid unnecessary re-renders.ChangeDetectorRef and NgZone for manual management:constructor(private cdr: ChangeDetectorRef) {}
update() {
this.value = newValue;
this.cdr.detectChanges(); // manually trigger check
}
Important:
OnPush doesn't mean component will never update. It still reacts to input data changes and events (click, input).
Important:
Using ChangeDetectorRef.detectChanges() is considered bad practice, as it breaks automatic change detection mechanism, triggers unnecessary rendering that may not be needed and creates unpredictable behavior. For optimization usually use markForCheck() or detatch/reattach (never seen the latter on live project)
Angular has reactive programming mechanisms: signals, observables and inputs. Better use them for correct rendering.
Read more here.