Sub topic 2
Enabling Zoneless Angular Applications
This chapter assumes you can build standalone Angular components, use signals, and work with Promises, timers, and events. It also assumes you know the default change-detection model.
Enabling zoneless mode and removing Zone.js
In a zone-based application, Zone.js patches asynchronous browser APIs such as timers and events. Angular uses those patches as a signal to check component views. Zoneless mode removes that broad notification mechanism. Angular instead checks views when an Angular-aware notification says that state may have changed.
Add provideZonelessChangeDetection() to the application providers:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { App } from './app/app';
bootstrapApplication(App, {
providers: [provideZonelessChangeDetection()],
});Remove "zone.js" from the polyfills arrays in angular.json. If the project has a polyfills.ts file, also remove its zone.js import. Removing these references prevents Zone.js from entering the browser and test bundles.
"polyfills": []What schedules change detection now
Angular schedules change detection after notifications such as:
- A signal read by a template changes.
- A user event handled by a template runs.
ChangeDetectorRef.markForCheck()is called.- A component input is set through Angular.
- A view is attached while marked dirty.
- An
AsyncPipereceives a new value.
The notification causes Angular to schedule a check. Angular does not need to inspect every timer or Promise callback.
Handling non-signal state
Prefer signals for state displayed in templates:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<button (click)="increment()">Clicked {{ count() }} times</button>`,
})
export class Counter {
protected readonly count = signal(0);
increment() {
this.count.update(value => value + 1);
}
}For legacy fields changed by external asynchronous code, call markForCheck() after changing the field. The AsyncPipe is another good option because each emitted value marks its view for checking.
this.seconds++;
this.cdr.markForCheck();Exercise
A timer increments a plain component field, but the template does not change in a zoneless app. What should you do?
Show answer
Convert the field to a signal, or call ChangeDetectorRef.markForCheck() after updating it. An observable rendered with AsyncPipe is another suitable option.