How to use async pipe in Angular

The async pipe in Angular provides automatic subscription management for observables and promises in templates, eliminating manual subscription handling and memory leaks. As the creator of CoreUI, a widely used open-source UI library, I’ve used async pipes extensively in Angular applications to create reactive user interfaces. From my 25 years of experience in web development and 11 years with Angular, the most effective approach is to use async pipes directly in templates for observable data binding. This pattern provides automatic subscription lifecycle management and clean reactive programming.

Use the async pipe in templates to automatically subscribe to observables and handle subscription lifecycle.

import { Component } from '@angular/core'
import { Observable } from 'rxjs'
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'app-users',
  template: `
    <div *ngIf="users$ | async as users; else loading">
      <div *ngFor="let user of users">
        {{ user.name }} - {{ user.email }}
      </div>
    </div>
    <ng-template #loading>
      <div>Loading users...</div>
    </ng-template>
  `
})
export class UsersComponent {
  users$: Observable<any[]>

  constructor(private http: HttpClient) {
    this.users$ = this.http.get<any[]>('/api/users')
  }
}

The async pipe automatically subscribes to the observable when the component initializes and unsubscribes when the component is destroyed, preventing memory leaks. Using the as syntax with *ngIf provides both null checking and type casting for the template variable. The pipe handles loading states naturally - the template shows nothing until data arrives, or you can use *ngIf; else for explicit loading templates. Multiple async pipes on the same observable create multiple subscriptions, so use template variables with as to avoid this.

This is the same async pipe pattern we use in CoreUI Angular templates for efficient data binding and memory management. For complex data transformations, combine async pipe with RxJS operators like map, filter, or switchMap in your component’s observable streams.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author