Performance: Zone.js and automatic detection
This concept affects how Angular detects changes and updates the UI, impacting interaction responsiveness and rendering speed.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-root', template: `<button (click)="increment()">Increment</button><p>{{count}}</p>` }) export class AppComponent { count = 0; constructor(private ngZone: NgZone) {} increment() { this.ngZone.runOutsideAngular(() => { setTimeout(() => { this.count++; this.ngZone.run(() => {}); }, 1000); }); } }
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<button (click)="increment()">Increment</button><p>{{count}}</p>` }) export class AppComponent { count = 0; increment() { setTimeout(() => { this.count++; }, 1000); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Automatic detection on every async event | Many unnecessary checks | Multiple reflows if UI updates | High paint cost due to frequent updates | [X] Bad |
| Manual zone control with runOutsideAngular | Minimal checks only on real changes | Single reflow per update | Lower paint cost with fewer updates | [OK] Good |
Zone.js in Angular?NgZone.run() to run code inside Angular's zone for UI updates.constructor(private zone: NgZone) {
setTimeout(() => {
this.zone.run(() => {
this.message = 'Updated!';
});
}, 1000);
}zone.run(), so Angular detects changes.constructor(private zone: NgZone) {
this.zone.runOutsideAngular(() => {
setTimeout(() => {
this.message = 'Changed!';
}, 500);
});
}runOutsideAngular does not trigger Angular change detection.runOutsideAngular() avoid triggering UI updates repeatedly.zone.run() to update UI and trigger change detection.Pass the test and this pattern moves unknown