Angular & Signals (283 Qs)•Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)
What is NgZone?
Angular provides a service called NgZone which creates a zone named angular to automatically trigger change detection when the following conditions are satisfied.
- When a sync or async function is executed.
- When there is no microTask scheduled.
Practical Code Example
typescript
// NgZone: Running expensive operations outside Angular change detection:
import { Component, NgZone, inject } from '@angular/core';
@Component({ selector: 'app-canvas', standalone: true, template: '' })
export class CanvasComponent {
private ngZone = inject(NgZone);
startAnimation() {
this.ngZone.runOutsideAngular(() => {
// Runs 60fps animation loop without triggering change detection on every frame!
requestAnimationFrame(this.renderLoop);
});
}
}