Formatting Data in Angular 2 Templates with Pipes

Using the Async Pipe for Future Data

The async pipe is a special kind of impure pipe that either waits for a promise to resolve to display data or subscribes to an observable to display the emitted values. Let's see an example of this in action.


import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';

  selector: 'my-app',
  template: `
    <h1>Counting Down From {{ countDown }}!</h1>
    <h2 *ngIf="!countCompleted">{{ count$ | async }}</h2>
    <h2 *ngIf="countCompleted">{{ message }}</h2>
export class AppComponent {
  countCompleted: boolean;
  countDown: number;
  count$: Observable<number>;

    this.countDown = 5;
    this.message = "Happy birthday!"
    this.countCompleted = false;

    this.count$ = Observable
                    .map(i => this.countDown - i)
                    .takeWhile(i => i > 0)
                    .finally(() => this.countCompleted = true);

We can also see this example live:

Here we're creating an observable in AppComponent which counts down from 5 over a 1 second interval. In our template, we're displaying the current count using the async pipe. When the countdown is over, we replace the count with a message saying "Happy birthday!". We can customize where we want to start the count at and the message we display afterwards in the constructor of AppComponent.

Additional Reading

List of Pipes in Angular 2

Pipes Guide