
Zoneless Angular: What Schedules Rendering Without zone.js
- كاتب موثّق
- Angular 22
محتويات المقال
cdr.detectChanges() after every assignment, forty of them across the codebase. The inbox works again. Then two bug reports arrive: the unread badge in the header is stuck, and after a reconnect that replays 200 messages, the tab stutters while the inbox renders 200 times in a row.
The common misconception
detectChanges() wherever state changes.
NgZone.run(), and the next most popular answer was detectChanges(). Both suggest that zone.js is the engine and that, without the engine, you push the car yourself. The half-truth is real: in a zoneless app, something has to tell Angular that state changed. But your code already sends those signals, often literally, and Angular schedules the render itself.
What actually happens
zone.js was a trigger, never the detector
Notifications replace the guess
markForCheck() is called (the async pipe does it for you), setInput() sets an input, or a dirty view is attached. The API reference adds two more: removing a view and registering a render hook. The first notification schedules one pass for shortly after the current task, and every notification that arrives before it runs joins that same pass. Ten signal writes in one callback cost one render, not ten.
Why detectChanges() is the wrong translation
detectChanges() isn't a notification; it's a check that runs synchronously, right now, on one view and its children. That explains both bug reports. Each replayed message re-rendered the inbox on the spot, 200 renders in one task where one would do. And the header isn't a child of the inbox, so the badge it shows was never checked. The calls also leave the cause in place: state that Angular can't see change, so the next developer who assigns a field and forgets the call brings the bug back. Angular's docs pair detectChanges() with detach(), for views you deliberately check by hand.
import { ChangeDetectorRef, Component, ElementRef } from '@angular/core';import { inject, viewChild } from '@angular/core';@Component({ selector: 'app-inbox', templateUrl: './inbox.html' })export class Inbox { private readonly cdr = inject(ChangeDetectorRef); private readonly list = viewChild.required<ElementRef<HTMLElement>>('list'); messages: Message[] = []; constructor() { inject(ChatSocket).messages$.subscribe((m) => { this.messages = [...this.messages, m]; this.cdr.detectChanges(); // renders Inbox right now, once per message this.list().nativeElement.lastElementChild?.scrollIntoView(); }); }}import { Component, ElementRef, afterRenderEffect } from '@angular/core';import { inject, viewChild } from '@angular/core';import { toSignal } from '@angular/core/rxjs-interop';import { scan } from 'rxjs';@Component({ selector: 'app-inbox', templateUrl: './inbox.html' })export class Inbox { private readonly list = viewChild.required<ElementRef<HTMLElement>>('list'); readonly messages = toSignal( inject(ChatSocket).messages$.pipe( scan((all: Message[], m) => [...all, m], []), ), { initialValue: [] }, ); constructor() { // Runs after the DOM is updated, each time messages() has changed afterRenderEffect({ write: () => { this.messages(); // the dependency that re-runs this callback this.list().nativeElement.lastElementChild?.scrollIntoView(); }, }); }}afterRenderEffect(), which runs after Angular has updated the DOM and re-runs whenever a signal it read changed. The wrong version only found the new <li> because it forced a render first. Any badge that reads the same state through a signal updates too, wherever it sits in the tree.
Waiting for a render without onStable
NgZone.onStable or onMicrotaskEmpty. In a zoneless app those Observables never emit, and NgZone.isStable is always true, so that code silently stops working. The replacements are the : afterNextRender() for one render, like initializing a chart library, and afterEveryRender() for work that spans several. Prefer an explicit phase, such as write or read, because a bare callback runs in mixedReadWrite, which the docs warn can hurt performance. NgZone.run() and runOutsideAngular() can stay: they're compatible with zoneless, and removing them from a library can slow down apps that still use zone.js.
markForCheck() in legacy code | |
detectChanges() after each change | |
NgZone.onStable or onMicrotaskEmpty to wait for a render | afterNextRender() or afterEveryRender() |
PendingTasks.run() around async work that must finish first | |
fixture.detectChanges() in tests | await fixture.whenStable() |
How to apply it in your project
Confirm the app is really zoneless Make sure provideZoneChangeDetection()isn't overriding the default, then removezone.jsandzone.js/testingfrom the polyfills inangular.jsonand uninstall the package.Turn forced renders into notifications Search for detectChanges(). Where it follows an assignment, make the state a signal and delete the call. Keep it only for views you detached on purpose.Replace zone-stability code Swap onStableandonMicrotaskEmptysubscriptions forafterNextRender()orafterEveryRender(), and deleteisStablechecks.Register async work for SSR Wrap async work that must finish before the server serializes the page in PendingTasks.run().HttpClientrequests and router navigations are already tracked.
Key takeaways
zone.js never detected changes; it told Angular when to run change detection, after every async task. Zoneless Angular runs the same change detection, scheduled by notifications: signals, listeners, markForCheck()andsetInput().detectChanges()renders one subtree synchronously; a notification schedules one pass for everything that changed.Replace zone-stability hooks with afterNextRender(),afterEveryRender()andPendingTasks.
التعليقات (0)