Sub topic 8
Handling non-signal state with markForCheck and the async pipe
This chapter assumes you can build standalone components, use signal and computed, and know how OnPush change detection works. It also assumes you have enabled zoneless mode with provideZonelessChangeDetection(). Here you learn what to do with state that is not held in a signal.
Why plain fields stop updating
In a zone-based app, Zone.js patches setTimeout, setInterval, DOM events and Promises. After any of them runs, Angular checks the component tree. A plain field such as seconds = 0 changes inside a timer, and the view updates because Zone.js announced that "something happened".
In a zoneless app nothing makes that announcement. Angular schedules a check only when it receives a notification. The main notification sources are:
- A signal that is read in a template changes its value.
- A template or host listener event handler runs.
markForCheck()is called.- The
asyncpipe receives a new value. - A view is attached or removed, or a component is created through the router or
ViewContainerRef.
A plain field changed in a timer matches none of these. The field has the new value, but the screen still shows the old one.
The preferred fix: use a signal
If you can change the field, change it to a signal. Reading the signal in the template registers a dependency, and writing to it notifies Angular. No extra call is needed.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-signal-timer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class SignalTimer {
protected readonly seconds = signal(0);
constructor() {
setInterval(() => this.seconds.update((s) => s + 1), 1000);
}
}This is the same behavior as the markForCheck() version below, with less to remember. Use the techniques in the rest of this chapter when you cannot or do not want to convert the state.
markForCheck for state you cannot convert
ChangeDetectorRef.markForCheck() marks the component and all its ancestors up to the root as needing a check. In zoneless mode it also tells the change detection scheduler to run. That second effect matters: in a zone-based OnPush app, markForCheck() only flagged the views and relied on Zone.js to trigger the next run.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-legacy-timer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class LegacyTimer {
private readonly cdr = inject(ChangeDetectorRef);
protected seconds = 0;
constructor() {
setInterval(() => {
this.seconds++;
this.cdr.markForCheck();
}, 1000);
}
}Several points about this code:
- The field is changed first, then
markForCheck()is called. The check runs later, so the order inside the callback does not matter, but both must happen. - Calls are batched. If a callback calls
markForCheck()ten times, Angular still runs one change detection pass. - The component must use
OnPush, or be compatible with it. Zoneless mode is designed aroundOnPushsemantics, and aDefaultcomponent is only checked when a parent that is being checked reaches it.
Where markForCheck is needed
Typical cases are:
- Callbacks from third-party libraries that are not wrapped in Angular event bindings, such as a map widget or a WebSocket client.
setTimeout,setIntervalandrequestAnimationFramecallbacks that write plain fields.- Promise
thenhandlers andasyncfunctions that write plain fields. - RxJS
subscribecallbacks that write plain fields.
Common mistakes
- Calling markForCheck before the change. If the field is written after the call, the scheduled check still sees the new value in most cases because the check is deferred. Do not rely on this. Write the field first.
- Mutating an object a child receives as an input. Inputs are compared by reference. If a parent mutates
user.namein place, a child usingOnPushis not refreshed, even when the parent is checked. Replace the object or use signals. - Scattering markForCheck everywhere. Many calls usually signal that the state should be in signals or in an observable consumed by
async.
The async pipe
The async pipe subscribes to an Observable or Promise in the template, unsubscribes when the component is destroyed, and calls markForCheck() each time a new value arrives. That makes it work in zoneless apps without further code.
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-clock',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Elapsed: {{ elapsed$ | async }} s</p>`,
})
export class Clock {
protected readonly elapsed$ = interval(1000).pipe(map((n) => n + 1));
}Because the pipe handles both subscription and notification, existing RxJS-heavy code often needs no changes. The things to check are:
- Every observable value that reaches the view must pass through
async, or throughtoSignal(). - Subscribing manually and assigning the result to a field bypasses the pipe. That is the case that needs
markForCheck(). - Several
asyncpipes on one stream create several subscriptions. For a cold observable, such as an HTTP request, that means several requests. Use@if (data$ | async; as data)once, or share the stream.
toSignal as a bridge
toSignal() from @angular/core/rxjs-interop turns an observable into a signal. The signal changes whenever the observable emits, so the view is notified through the signal mechanism.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-clock-signal',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Elapsed: {{ elapsed() }} s</p>`,
})
export class ClockSignal {
protected readonly elapsed = toSignal(interval(1000).pipe(map((n) => n + 1)), {
initialValue: 0,
});
}Without initialValue, the signal's type includes undefined until the first emission. toSignal() also unsubscribes when the injection context is destroyed, so it must be called in a constructor, field initializer or runInInjectionContext.
Choosing between the three
| Situation | Best choice | Reason |
|---|---|---|
| State you own and can change | `signal` | Notifies Angular on write. No extra calls. |
| An observable displayed in the template | `async` pipe or `toSignal` | Both notify on each emission and clean up. |
| A callback from code you cannot change | Plain field plus `markForCheck()` | The only way to send the notification. |
| Derived values | `computed` | Updates when its source signals change. |
Edge cases
Events handled by a listener
A template event such as (click)="save()" marks the component for check automatically after the handler runs. Fields written synchronously in that handler appear on screen. Fields written later, for example after await or in a setTimeout inside the handler, are not covered. The notification happens when the handler returns, so a later write needs its own markForCheck() or a signal.
Listeners added by hand
A listener added with addEventListener or renderer.listen outside the template is not a template listener. Writes to plain fields inside it need markForCheck(). Renderer2.listen does not notify on its own.
Using the ChangeDetectorRef of a different component
inject(ChangeDetectorRef) in a component gives that component's reference. In a service, injecting it does not give you a useful view reference. Have the service expose a signal or an observable and let the component consume it.
Calling detectChanges instead
cdr.detectChanges() runs a check on that view immediately and synchronously. It works in zoneless mode, but it skips batching and can run many checks in one task. It is also unsafe to call during another check. Prefer markForCheck().
Putting it together
The service below keeps a Promise-based legacy API but reaches the view through a signal. The component needs no markForCheck().
import { ChangeDetectionStrategy, Component, Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class QuoteService {
readonly quote = signal('Loading...');
constructor() {
setTimeout(() => this.quote.set('Zoneless works.'), 500);
}
}
@Component({
selector: 'app-quote',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<blockquote-text>{{ service.quote() }}</blockquote-text>`,
})
export class Quote {
protected readonly service = inject(QuoteService);
}Note that this snippet needs inject imported from @angular/core and a registered custom element schema for blockquote-text. Replace that tag with <p> when you run it, and add inject to the import list.
Exercise
A component subscribes to a WebSocket stream in its constructor with socket$.subscribe(msg => this.last = msg), where last is a plain field shown in the template. The component uses OnPush and the app is zoneless. The view never updates. Give two different fixes, and say which you prefer.
Show answer
Fix 1: inject ChangeDetectorRef and call this.cdr.markForCheck() after assigning this.last in the subscribe callback. Fix 2: remove the manual subscription, expose last = toSignal(socket$) (or use socket$ | async in the template). Both notify Angular when a message arrives. The second is preferred because it needs no manual notification and it also handles unsubscribing when the component is destroyed. The manual subscribe in the original code also never unsubscribes.
Exercise
In a template handler (click)="load()", the method does this.loading = true; await fetch(url); this.loading = false; with loading as a plain field. The spinner appears but never disappears. Why, and how do you fix it?
Show answer
The click listener notifies Angular when the handler returns, which happens at the first await. That check sees loading = true. The later assignment loading = false happens after the notification, and nothing announces it. Fix it by making loading a signal and calling loading.set(false), or by calling markForCheck() after the second assignment.