When you update a variable in TypeScript, the HTML view updates instantly.
The mechanism responsible for syncing the data to the view is called "Change Detection".
Understanding how to optimize this system is the key to building high-performance enterprise applications.
By default, Angular uses a library called Zone.js to trigger Change Detection.
Zone.js intercepts every single asynchronous event in the browser (clicks, timers, HTTP requests).
After an event occurs, Angular assumes data might have changed, so it scans every single component from top to bottom.
While convenient, scanning the entire component tree on every click is very bad for performance in massive applications!
To fix performance issues, you can switch a component to the OnPush change detection strategy.
When a component is set to OnPush, Angular skips checking that component during normal cycles.
It will only update the component if an explicitly defined @Input prop changes reference, or if an event fires inside it.
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-optimized',
template: '<p>{{ data }}</p>',
// Tells Angular to skip checking this component unless inputs change
changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent { }
If you use OnPush, you might occasionally need to force Angular to update the component manually.
You can achieve this by injecting the ChangeDetectorRef service into your component.
Calling this.cdr.detectChanges() forces Angular to re-evaluate the component immediately.
import { ChangeDetectorRef } from '@angular/core';
export class ManualComponent {
constructor(private cdr: ChangeDetectorRef) {}
updateDataManually() {
this.data = 'New Value';
// Forces the UI to update with the new value
this.cdr.detectChanges();
}
}
As discussed in the previous chapter, modern Angular is migrating toward Signals.
Signals completely bypass Zone.js.
When a Signal updates, Angular updates the exact DOM node associated with it, making OnPush and manual change detection increasingly obsolete!
What library does Angular use by default to intercept browser events and trigger automatic change detection?
If a component uses the OnPush strategy, how can you manually force it to update the UI after a background operation?