← Back to Angular, page 6

angular-0120 · Medium mid

When and how do you use NgZone.runOutsideAngular, and how do you get back into the zone to update the UI?

Code started inside runOutsideAngular does not trigger change detection when its callbacks run. Use it for high frequency events such as mousemove or scroll and for timers that do not change the UI, then call ngZone.run or update a signal only when the UI must change.

Full answer

With zone.js, every event, timer and promise started inside the Angular zone can trigger a change detection pass when it finishes. For a mousemove listener that fires 60 times a second, that means 60 passes per second even if the template does not change.

NgZone.runOutsideAngular(fn) runs fn in the parent zone. Anything the function starts (event listeners, setInterval, requestAnimationFrame) keeps running in that outer zone, so its callbacks do not notify Angular. Use it when:

  • Handling high frequency events (scroll, mouse move, resize, drag).
  • Running animations with requestAnimationFrame.
  • Starting third party libraries (charts, maps) that attach many listeners and timers.
  • Running long polling that rarely updates the UI.

To update the UI from outside the zone:

  • Use a signal. In recent versions, setting a signal that a template reads schedules change detection, even outside the zone (the signal notifies the scheduler). This is the simplest way.
  • Or call ngZone.run(() => ...), which enters the zone and triggers a pass when it finishes.
  • Or call ChangeDetectorRef.markForCheck() plus detectChanges() for a specific view.

Cautions:

  • Zoneless applications (Angular 20.2 and newer) have no NgZone work to do. runOutsideAngular still works and just runs the function, so code that uses it stays valid, but it is no longer a performance tool there.
  • Do not forget cleanup. Listeners added outside the zone still need to be removed (use DestroyRef).
  • NgZone.isInAngularZone() helps with debugging.
  • Measure first. Moving code outside the zone makes data flow harder to follow, so do it only where the profiler shows a cost.

For many apps the better long term answer is signals with zoneless change detection, which avoids the problem.

typescript
import { Component, DestroyRef, ElementRef, NgZone, afterNextRender, inject, signal } from '@angular/core';

@Component({
  selector: 'app-pointer-tracker',
  template: `
    <div #area class="area">Move the mouse here</div>
    <p>Last stable position: {{ position() }}</p>
  `,
})
export class PointerTrackerComponent {
  private readonly zone = inject(NgZone);
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly destroyRef = inject(DestroyRef);

  readonly position = signal('none');
  insideZoneWhenHandled: boolean | null = null;

  constructor() {
    afterNextRender(() => {
      const area = this.host.nativeElement.querySelector('.area') as HTMLElement;

      this.zone.runOutsideAngular(() => {
        const onMove = (event: MouseEvent) => {
          this.insideZoneWhenHandled = NgZone.isInAngularZone();
          // Update the UI only for a meaningful change, not on every move.
          if (event.clientX % 50 === 0) {
            this.position.set(`${event.clientX},${event.clientY}`);
          }
        };
        area.addEventListener('mousemove', onMove);
        this.destroyRef.onDestroy(() => area.removeEventListener('mousemove', onMove));
      });
    });
  }
}

Angular 20.3, strict template check passes. A Karma test checks that the listener runs outside the Angular zone and that the signal value is updated only for the chosen positions.

Key points

  • `runOutsideAngular` stops zone.js from triggering change detection for the callbacks started inside.
  • Use it for scroll, mouse move, animation frames and third party libraries.
  • Return to the UI with a signal update or `ngZone.run`.
  • Clean up listeners, and measure before using it. In zoneless apps it is not a performance tool.

Common mistakes

  • Updating a plain property from outside the zone and seeing no UI change.
  • Forgetting to remove listeners added outside the zone.
  • Using it everywhere without measuring.

Follow-ups

  • How does a signal update from outside the zone reach the screen?
  • How would you test that the handler does not trigger change detection?
  • What replaces this technique in zoneless apps?

Tips

  • Start with the 60 passes per second example.
  • Name the three ways back into the UI.
  • Mention zoneless to show current knowledge.

Evaluation rubric

  • Explains why and when to leave the zone.
  • Shows how to update the UI safely.
  • Mentions cleanup and zoneless.