
Angular Doesn't Watch Your Variables: How Change Detection Really Works
- كاتب موثّق
- Angular 22
محتويات المقال
console.log in the promise callback prints Saved, so the field holds the right value. The screen just never hears about it.
The common misconception
this.status = 'Saved' is all it takes, and the DOM updates the moment the value changes.
setTimeout, network requests and event listeners, Angular ran change detection after each of them, so an assignment in a callback reached the screen almost instantly. Some other frameworks really do track property writes, through proxies or compiled setters, which makes the model feel universal. The half-truth is that the screen did update after async work. A watcher was never the reason, though; zone.js was, and Angular 22 apps don't load it by default.
What actually happens
Change detection is a pass, not a watcher
this.status = 'Saved' is a plain JavaScript property write: no proxy, no setter, nothing that tells Angular it happened.
Something has to schedule the pass
a bound template or host listener ran, like (click);a signal that a template reads was updated; markForCheck()was called, which theasyncpipe does for you;ComponentRef.setInput()set an input;a view that one of the above marked dirty was attached.
setTimeout firing or a WebSocket message arriving isn't on the list.
OnPush decides which components get checked
ChangeDetectionStrategy.Eager, the new name for the deprecated Default.
import { Component, inject } from '@angular/core';@Component({ selector: 'app-save-button', template: ` <button (click)="save()">Save draft</button> <span>{{ status }}</span> `,})export class SaveButton { private readonly drafts = inject(DraftApi); status = ''; save(): void { this.status = 'Saving...'; // shows: the click schedules a pass this.drafts.save().then(() => { this.status = 'Saved'; // never shows: nothing schedules a pass }); }}import { Component, inject, signal } from '@angular/core';@Component({ selector: 'app-save-button', template: ` <button (click)="save()">Save draft</button> <span>{{ status() }}</span> `,})export class SaveButton { private readonly drafts = inject(DraftApi); readonly status = signal(''); save(): void { this.status.set('Saving...'); this.drafts.save().then(() => { this.status.set('Saved'); // marks SaveButton, schedules a pass }); }}status.set('Saved') updates a signal the template reads. That's one of the notifications, so Angular marks SaveButton and schedules a pass, and the label updates.
markForCheck() marks the view and its ancestors and, in a zoneless app, schedules the pass:
import { ChangeDetectorRef, Component, inject } from '@angular/core';@Component({ selector: 'app-legacy-status', template: `<span>{{ status }}</span>`,})export class LegacyStatus { private readonly cdr = inject(ChangeDetectorRef); private readonly drafts = inject(DraftApi); status = 'Saving...'; constructor() { this.drafts.save().then(() => { this.status = 'Saved'; this.cdr.markForCheck(); // the notification the field can't send }); }}Dev mode checks your templates twice
ExpressionChangedAfterItHasBeenCheckedError) if a binding's value changed in between. It's the other side of the same model: Angular renders whatever your templates return during a pass, and it expects reading them not to change anything. A getter that returns Math.random(), or a child that updates its parent's state while it's being checked, trips it. Production builds skip this check.
setTimeout or subscribe() | |
(click) | |
markForCheck() after an assignment |
How to apply it in your project
Convert fields that change after async work Any field assigned after await,.then(),setTimeoutorsubscribe()and read by a template should become a signal. Update it withset()orupdate().Render Observables through the async pipe The asyncpipe callsmarkForCheck()on every emission, so a stream rendered with it updates without extra code.Replace mutations with new values Instead of items.push(item), writeitems.update((list) => [...list, item]), so both the signal and OnPush children see a change.Keep markForCheck() for legacy code Where a component can't move to signals yet, call markForCheck()after every assignment that happens outside a template listener, and plan its move to signals.
Key takeaways
Angular doesn't watch fields: it re-evaluates templates in passes and compares results with the last render. In Angular 22 apps, only notifications schedule a pass: signals read by templates, template or host listeners, markForCheck()andsetInput().OnPush, the default since v22, limits each pass to the components that were marked. State that changes after async work belongs in a signal; markForCheck()is the fallback, not the fix.
التعليقات (0)