Loading...
Loading...
NgZone is a service in Angular used for managing execution zones (execution context) and triggering change detection. It's based on zone.js library and allows Angular to track all asynchronous operations, such as setTimeout, Promise, XHR, etc.
Angular uses NgZone to:
click, HTTP, setTimeout);When asynchronous event occurs (e.g., setTimeout, fetch, input), Angular automatically:
NgZone;Change Detection to update UI.import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-zone-demo',
template: `<p>{{progress}}%</p>`
})
export class ZoneDemoComponent {
progress = 0;
constructor(private ngZone: NgZone) {}
startProgress() {
this.progress = 0;
this.increaseProgress();
}
// Without exiting zone — will trigger change detection every step
increaseProgress() {
if (this.progress < 100) {
setTimeout(() => {
this.progress += 1;
this.increaseProgress();
}, 10);
}
}
}
Sometimes you don't need to trigger change detection too often. In this case you can use runOutsideAngular():
this.ngZone.runOutsideAngular(() => {
this.progress = 0;
const timer = setInterval(() => {
this.progress += 1;
if (this.progress >= 100) {
clearInterval(timer);
// Return back to Angular zone to update UI
this.ngZone.run(() => {
console.log("Completed!");
});
}
}, 10);
});
runOutsideAngular() — runs code outside Angular zone, so change detection is not triggered every time.run() — manually return to Angular context and initiate UI update.| What Does NgZone Do? | Advantages |
|---|---|
| Tracks asynchronous operations | Automatic UI updates |
| Triggers Change Detection | Convenient when interacting with DOM |
Allows exiting zone (runOutsideAngular) | Performance improvement |
| Allows manually returning to Angular zone | Control over interface updates |