What is NgZone in Angular?
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.
Why NgZone?
Angular uses NgZone to:
- automatically trigger change detection after asynchronous operations complete;
- track external events (e.g.,
click,HTTP,setTimeout); - allow performance optimization by manually managing change detection triggering.
How NgZone Works
When asynchronous event occurs (e.g., setTimeout, fetch, input), Angular automatically:
- Enters
NgZone; - Executes asynchronous task;
- After completion — calls
Change Detectionto update UI.
Example
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);
}
}
}
What If We Exit Zone?
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.
Summary
| 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 |