InterviewHubPRO
Section Overview
Q243

Question 243 of 283

Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)

86%
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.

  1. When a sync or async function is executed.
  2. 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);
    });
  }
}