What is Zone.js in Angular?
Answer
Zone.js is a library that creates execution contexts called "zones" — it patches all browser async APIs (setTimeout, setInterval, Promise, XHR, event listeners, etc.) to intercept when they are called and when they complete. Angular uses Zone.js to automatically know when to run change detection. How it works: Angular creates one zone (NgZone) for the application. When an async operation (click event, HTTP response, timer) completes, Zone.js notifies Angular, which then triggers change detection across the component tree. Without Zone.js: developers would need to manually call ChangeDetectorRef.detectChanges() or markForCheck() after every async operation to update the view. Drawbacks of Zone.js: (1) Triggers change detection very broadly — any async event, even unrelated to UI, triggers the whole tree check; (2) Increases bundle size (~70KB minified+gzip); (3) Can cause "ExpressionChangedAfterItHasBeenCheckedError" in dev mode. Running code outside Angular's zone: this.ngZone.runOutsideAngular(() => { performanceHeavyOperation(); }) — prevents change detection for this operation. Re-enter to update UI: this.ngZone.run(() => { this.updateUI(); }). Zoneless Angular (future): Angular is working on making Zone.js optional. Angular 17 introduced experimental zoneless support using Signals for fine-grained change detection. provideExperimentalZonelessChangeDetection() in main.ts.