Sub topic 9
The async pipe and automatic marking
This chapter assumes you know Angular components and templates, RxJS observables and promises at a basic level, and the OnPush strategy from the previous chapters. It shows how the async pipe keeps an OnPush component up to date without manual calls to markForCheck.
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. If you subscribe in the class and assign the value to a field, the template does not update until something else marks the component dirty.
import { ChangeDetectionStrategy, Component, OnInit, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-users-manual',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Users loaded: {{ count }}</p>`,
})
export class UsersManual implements OnInit {
private http = inject(HttpClient);
count = 0;
ngOnInit() {
this.http.get<unknown[]>('/api/users').subscribe((users) => {
this.count = users.length; // the template may not refresh
});
}
}This pattern is fragile. It also needs an unsubscribe step for long-lived streams. The async pipe handles both concerns.
What the pipe does
The async pipe subscribes to an observable or promise from inside the template. Each time a new value arrives, it stores the value and calls markForCheck on the component's change detector. That marks the component and its ancestors dirty, so the next change detection cycle checks the view. When the component is destroyed, the pipe unsubscribes.
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-users',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AsyncPipe],
template: `
@if (users$ | async; as users) {
<p>Users loaded: {{ users.length }}</p>
} @else {
<p>Loading...</p>
}
`,
})
export class Users {
users$ = inject(HttpClient).get<unknown[]>('/api/users');
}The template holds the only subscription. When the response arrives, the pipe marks the component dirty and the view shows the count.
Things to know
- Marking only flags the view. A cycle still has to run. In a Zone.js application the HTTP callback runs inside the Angular zone, so a cycle follows. In a zoneless application,
markForCheckalso schedules a cycle. - Use one subscription per observable. Each
| asyncin a template creates its own subscription, and a cold observable such as an HTTP request runs once per subscription. Bind once with@if (x$ | async; as x)and readxinside the block. - The pipe returns
nullbefore the first emission. Handle that case, as the@elsebranch above does, or the template may read properties ofnull. - A new observable reference means a new subscription. If you build the observable in a getter or a method called from the template, such as
getUsers() | async, each check creates a fresh stream and the pipe resubscribes in a loop. Assign the observable to a field once. - A mutated object emitted by a stream is not a new value. Emit new references, as in the immutable updates chapter.
Comparing the options
| Approach | Marks component dirty | Unsubscribes for you |
|---|---|---|
| Manual `subscribe` and field | No | No |
| Manual `subscribe` plus `markForCheck` | Yes, if you call it | No |
| `async` pipe | Yes, on each emission | Yes |
Exercise
A component uses OnPush and has the template {{ (price$ | async) }}. Why does the view update when price$ emits, even though no input changed and no event fired in the template?
Show answer
The async pipe subscribes to price$ and calls markForCheck on the component's change detector each time a value arrives. That marks the component and its ancestors dirty, so the next change detection cycle checks the view and renders the new value.
Exercise
Your template contains <p>{{ (user$ | async)?.name }}</p> and <p>{{ (user$ | async)?.email }}</p>, where user$ is an HTTP request. What problem does this cause, and how do you fix it?
Show answer
Each | async creates its own subscription, so the cold HTTP observable sends two requests. Use one subscription: @if (user$ | async; as user) { <p>{{ user.name }}</p> <p>{{ user.email }}</p> }.