Help Angular by taking a 1 minute survey!Go to surveyHome

AsyncPipe

Unwraps a value from an asynchronous primitive.

See more...

{{ obj_expression | async }}
      
      {{ obj_expression | async }}
    

NgModule

Input value

obj Observable | Promise

Description

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Usage notes

Examples

This example binds a Promise to the view. Clicking the Resolve button resolves the promise.

@Component({ selector: 'async-promise-pipe', template: `<div> <code>promise|async</code>: <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button> <span>Wait for it... {{ greeting | async }}</span> </div>` }) export class AsyncPromisePipeComponent { greeting: Promise<string>|null = null; arrived: boolean = false; private resolve: Function|null = null; constructor() { this.reset(); } reset() { this.arrived = false; this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; }); } clicked() { if (this.arrived) { this.reset(); } else { this.resolve !('hi there!'); this.arrived = true; } } }
      
      
  1. @Component({
  2. selector: 'async-promise-pipe',
  3. template: `<div>
  4. <code>promise|async</code>:
  5. <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
  6. <span>Wait for it... {{ greeting | async }}</span>
  7. </div>`
  8. })
  9. export class AsyncPromisePipeComponent {
  10. greeting: Promise<string>|null = null;
  11. arrived: boolean = false;
  12.  
  13. private resolve: Function|null = null;
  14.  
  15. constructor() { this.reset(); }
  16.  
  17. reset() {
  18. this.arrived = false;
  19. this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });
  20. }
  21.  
  22. clicked() {
  23. if (this.arrived) {
  24. this.reset();
  25. } else {
  26. this.resolve !('hi there!');
  27. this.arrived = true;
  28. }
  29. }
  30. }

It's also possible to use async with Observables. The example below binds the time Observable to the view. The Observable continuously updates the view with the current time.

@Component({ selector: 'async-observable-pipe', template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>' }) export class AsyncObservablePipeComponent { time = new Observable<string>((observer: Observer<string>) => { setInterval(() => observer.next(new Date().toString()), 1000); }); }
      
      @Component({
  selector: 'async-observable-pipe',
  template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {
  time = new Observable<string>((observer: Observer<string>) => {
    setInterval(() => observer.next(new Date().toString()), 1000);
  });
}