Angular 18, released May 22, 2024, introduced an experimental game-changer: zoneless Angular applications. This eliminates the Zone.js dependency, boosting performance, reducing overhead, and simplifying debugging. Let's delve into zoneless applications, their advantages, and how to experiment with this feature.
Change detection keeps the DOM synchronized with component data. Previously, Angular relied on Zone.js. Change detection triggered in these ways:
setTimeout
, setInterval
, Promise resolutions.ApplicationRef.tick()
, ChangeDetectorRef.detectChanges()
.Zone.js patched browser APIs, notifying Angular to initiate change detection. While effective, this added overhead and sometimes caused ExpressionChangedAfterItHasBeenCheckedError
.
Before zoneless change detection, Zone.js managed UI updates. This StackBlitz example illustrates:
ChangeDetectionStrategy.OnPush
, direct array mutations might not update the view unless the reference changes or change detection is manually triggered.AsyncPipe
simplifies observable handling, automatically subscribing and triggering change detection.These examples highlight Zone.js's role in change detection, setting the stage for Angular's improved zoneless architecture.
Removing Zone.js offers significant benefits:
ExpressionChangedAfterItHasBeenCheckedError
issues and zone-related complexities.Switching to zoneless requires configuration changes:
app.config.ts
, add:<code class="language-typescript">providers: [ provideExperimentalZonelessChangeDetection() ]</code>
Remove provideZoneChangeDetection()
if present.
import '*zone.js';
from your application files.angular.json
, remove zone.js
from the polyfills
array:<code class="language-json">"polyfills": []</code>
<code class="language-bash">npm uninstall zone.js</code>
This example demonstrates change detection without Zone.js:
Let's analyze each scenario:
Works as expected.
Requires this.changeDetectorRef.markForCheck();
or using signals:
Corrected version (with markForCheck
):
Corrected version (with signals):
The view doesn't update automatically:
Corrected version (with markForCheck
):
Using async
pipe is preferred.
Straightforward; use the async
pipe:
Use toSignal()
to convert observables to signals:
Summary:
markForCheck()
or signals.async
pipe.Angular 19 further refined zoneless application support, improving APIs, adding server-side rendering support, and enhancing testing. The Angular CLI now supports creating zoneless projects:
<code class="language-typescript">providers: [ provideExperimentalZonelessChangeDetection() ]</code>
The above is the detailed content of Embracing Zoneless in Angular: A New Era of Change Detection. For more information, please follow other related articles on the PHP Chinese website!