0
0
Angularframework~5 mins

Async pipe for template subscriptions in Angular

Choose your learning style9 modes available
Introduction

The async pipe helps you show data from streams like Observables or Promises directly in your template without extra code.

When you want to display data that updates over time, like live messages or sensor readings.
When you want to avoid manually subscribing and unsubscribing from Observables in your component code.
When you want to keep your template clean and simple by handling async data automatically.
When you want Angular to manage memory by unsubscribing automatically when the component is destroyed.
Syntax
Angular
{{ observableOrPromise$ | async }}
The async pipe works with both Observables and Promises.
It automatically subscribes to the Observable or waits for the Promise, then updates the template when data arrives.
Examples
Displays the latest value emitted by the userName$ Observable.
Angular
<p>{{ userName$ | async }}</p>
Uses async pipe with *ngIf to unwrap the Observable and assign its value to 'data'.
Angular
<div *ngIf="data$ | async as data">{{ data.title }}</div>
Displays the resolved value of a Promise named fetchDataPromise.
Angular
<p>{{ fetchDataPromise | async }}</p>
Sample Program

This component shows how to use the async pipe to display a timer that updates every second. The interval Observable emits numbers every 1000ms, and the async pipe unwraps the latest value to show in the template.

Angular
import { Component } from '@angular/core';
import { Observable, interval } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-async-pipe-demo',
  template: `
    <h2>Seconds elapsed: {{ seconds$ | async }}</h2>
  `
})
export class AsyncPipeDemoComponent {
  seconds$: Observable<number> = interval(1000).pipe(
    map(val => val + 1) // start counting from 1
  );
}
OutputSuccess
Important Notes

The async pipe automatically unsubscribes when the component is destroyed, preventing memory leaks.

Using async pipe keeps your component code simpler and easier to read.

If the Observable emits null or undefined, the template will show nothing until a valid value arrives.

Summary

The async pipe unwraps Observables or Promises directly in templates.

It automatically subscribes and unsubscribes, managing memory for you.

Use it to keep your component code clean and your UI reactive.