Sub topic 9
The async pipe and automatic marking
This chapter explains how the async pipe keeps an OnPush component up to date without a manual markForCheck() call. It also covers how the pipe manages subscriptions and the mistakes that break it. It assumes you know OnPush, input reference checks and ChangeDetectorRef.markForCheck() from the earlier chapters. It also assumes you know basic RxJS: Observable, subscribe and unsubscribe.
The problem the pipe solves
An OnPush component is checked only when an input reference changes, an event fires in its template, it is marked dirty, or a signal read in its template changes. Data that arrives from an observable fits none of these. A WebSocket message or an HTTP response does not touch the component's inputs.
The manual fix has three parts. You subscribe in the class, copy each value into a field, and call markForCheck(). You must also unsubscribe when the component is destroyed. The async pipe does all three inside the template.
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { timer } from 'rxjs';
@Component({
selector: 'app-clock',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds$ | async }}</p>`,
})
export class Clock {
seconds$ = timer(0, 1000);
}This component has no ChangeDetectorRef, no subscribe() call and no ngOnDestroy. The displayed number still updates every second, even though the component is OnPush.
What the pipe does internally
AsyncPipe is an impure pipe. Angular calls the transform method of a pure pipe only when its input reference changes. Angular calls an impure pipe's transform on every check of the view. The async pipe needs this because the observable reference stays the same while its latest value changes.
The pipe works in four steps:
- On the first
transformcall, it subscribes to the observable or promise and stores the subscription. - Each time the source emits, the pipe saves the value as its latest value and calls
markForCheck()on theChangeDetectorRefof the view that contains the pipe. - On each later
transformcall, it returns the saved latest value. - When the component is destroyed, the pipe's
ngOnDestroyunsubscribes.
Step 2 is the "automatic marking" in the chapter title. markForCheck() marks the component and all its ancestors dirty, up to the root. On the next change detection pass, Angular reaches the component and re-evaluates the binding, even though the component is OnPush. The binding then reads the new latest value.
Marking does not run change detection
markForCheck() only sets flags. Something else must start a change detection pass. In a Zone.js application, that something is usually the zone: the emission happened inside a timer, an HTTP callback or an event handler that the zone patched, so Angular runs a pass once that task finishes.
Initial values and null
The pipe returns null until the source emits for the first time. A cold HTTP observable has no value at first, so the template must handle null.
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { delay, of } from 'rxjs';
interface User {
name: string;
role: string;
}
@Component({
selector: 'app-profile',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
<p>{{ user.role }}</p>
} @else {
<p>Loading...</p>
}
`,
})
export class Profile {
user$ = of<User>({ name: 'Ada', role: 'Admin' }).pipe(delay(500));
}If the source emits synchronously, as a BehaviorSubject or of(...) does, the pipe returns that value on its first call and null never appears.
Two details matter here:
- The
@elsebranch also shows while a value that is falsy is emitted, such as0or an empty string, because@iftests truthiness. If0is a legitimate value, use@letwith an explicit comparison, or wrap the value in an object. - The type of
user$ | asyncisUser | null. Theas useralias inside@ifnarrows it toUser.
One subscription per pipe
Each | async in a template creates its own subscription. Writing user$ | async three times subscribes three times. For a cold observable such as an HTTP request, that sends three requests.
import { AsyncPipe } from '@angular/common';
import { Component } from '@angular/core';
import { Observable, defer, of } from 'rxjs';
@Component({
selector: 'app-fan-out',
imports: [AsyncPipe],
template: `
<p>{{ (user$ | async)?.name }}</p>
<p>{{ (user$ | async)?.role }}</p>
`,
})
export class FanOut {
user$: Observable<{ name: string; role: string }> = defer(() => {
console.log('subscribed'); // logs twice
return of({ name: 'Ada', role: 'Admin' });
});
}There are two common fixes. The first is to subscribe once and alias the value, as in the Profile example with @if (user$ | async; as user). The second is to share the stream with shareReplay({ bufferSize: 1, refCount: true }), so that all subscribers use one underlying subscription.
Keep the observable reference stable
The pipe compares the observable it receives with the one it subscribed to last time. If the reference differs, it unsubscribes from the old source and subscribes to the new one. Because transform runs on every check, an expression that builds a new observable each time causes trouble.
import { AsyncPipe } from '@angular/common';
import { Component } from '@angular/core';
import { Observable, timer } from 'rxjs';
@Component({
selector: 'app-bad-source',
imports: [AsyncPipe],
template: `<p>{{ getTick() | async }}</p>`,
})
export class BadSource {
getTick(): Observable<number> {
return timer(0, 1000); // a new Observable on every check
}
}Each check calls getTick() and gets a new observable. The pipe drops the old subscription and subscribes to the new one. The new subscription has not emitted yet, so the pipe returns null. The displayed value can then stay empty or flicker.
The fix is to create the observable once, in a field or in the constructor, as Clock does with seconds$. If the observable depends on an input, derive it from a BehaviorSubject or a signal, not from a method called in the template.
Errors and completion
If the source errors, the pipe rethrows the error from the subscription callback. That error reaches the application's ErrorHandler, and the template keeps showing the last good value. Handle errors in the stream with catchError and return a fallback value or a state object, so the template can render an error message.
When a source completes, the pipe keeps the last emitted value and does nothing more. It does not reset to null.
Async pipe or signals
Signals, covered in the next chapters, solve the same OnPush problem. toSignal() turns an observable into a signal and unsubscribes when the component is destroyed. The table compares the options.
| Approach | Subscribes | Unsubscribes | Marks the view | Initial value |
|---|---|---|---|---|
| Manual `subscribe` plus `markForCheck()` | You write it | You write it | You write it | Whatever you set |
| `async` pipe | Pipe, on first check | Pipe, on destroy | Pipe, on each emission | `null` until first emission |
| `toSignal()` | At the call, in an injection context | Automatically on destroy | The signal read in the template | `undefined` unless you pass `initialValue` |
The async pipe stays a good choice when a value only needs to be displayed and the observable already exists. Prefer toSignal() when the value feeds computed() signals or is read in the class code, because it gives a synchronous read without a template pipe.
Common mistakes
- Subscribing in
ngOnInit, assigning to a field and forgettingmarkForCheck()in an OnPush component. The field changes but the view does not update. - Using the pipe several times on one cold observable, which repeats the work or the request.
- Calling a method that returns a new observable in the template.
- Mutating an object that the pipe returned. The pipe returns the same reference, so an OnPush child that receives it as an input will not see the change.
Exercise
A component is OnPush and its template contains {{ (price$ | async)?.amount }} twice. price$ is an HttpClient call stored in a field. What happens when the component renders, and how would you change the template so that the request is sent once?
Show answer
Each | async subscribes separately, and HttpClient observables are cold, so the template sends two requests. Subscribe once and alias the value, for example @if (price$ | async; as price) { {{ price.amount }} ... }, or share the stream with shareReplay({ bufferSize: 1, refCount: true }) in the field definition. Both pipes then use one HTTP request.
Exercise
Why does markForCheck() inside the async pipe update an OnPush component's view, and what must still happen for the screen to change in a Zone.js app?
Show answer
markForCheck() marks the component and its ancestors dirty, so the next change detection pass does not skip the OnPush subtree and re-evaluates the binding. It does not start a pass itself. In a zone-based app, the emission must happen inside the Angular zone, such as in an HTTP callback or timer, so that the zone schedules a pass after the task.