Question presented to candidate:
"We have an Angular app that still uses Zone.js, and profiling shows change detection firing hundreds of times a second while a chart animates. What is NgZone, why is this happening, and how would runOutsideAngular help? Does any of this apply to a new Angular 22 app?"
What a strong answer should cover:
NgZoneis Angular's wrapper around a Zone.js zone named "angular"; every async task started inside it is tracked, and when the zone settles (onMicrotaskEmpty) Angular runs change detection.- Hot async work inside the zone (
requestAnimationFrame,mousemove,setInterval, WebSocket messages) therefore causes a run per task. runOutsideAngular(fn)starts work in the parent (root) zone, so its tasks do not trigger runs;run(fn)re-enters the Angular zone when the UI must update.- Also:
NgZone.isInAngularZone(),onStable/onUnstable, andprovideZoneChangeDetection({ eventCoalescing: true }). - Since v21 apps are zoneless by default and inject a no-op
NgZone; Zone.js is opt-in viaprovideZoneChangeDetection()plus the polyfill. With OnPush (v22 default), even re-entering the zone does not refresh a plain field; signals do.
Clarifying questions expected:
- "Is this app on
provideZoneChangeDetection()or already zoneless?" - "Is the hot work coming from our code or from a third-party library that schedules its own timers?"
Code / implementation expected: Yes β move a high-frequency loop outside the zone and re-enter with zone.run() for the final UI update.