Local variable in template for async pipe (angular 2+)

Since Angular 4.0.0-rc.1 (2017-02-24), you can use the enhanced *ngIf syntax. This let's you assign the result of an *ngIf condition in a template local variable:

<div *ngIf="profile$ | async as profile">
    <div>{{profile.username}}</div>
    <div>{{profile.email}}</div>
</div>

The updated *ngIf documentation goes into further detail and gives many good examples using async and *ngIf together.

Be sure to also check out the then and else statements of *ngIf.

Cory Rolan has made a short tutorial that you can digest in 5–10 minutes.


The best approach would be to create a new component, e.g. in this case app-profile and to pass profile | async to that component. Inside the component you can name the variable whatever you like.

<app-profile [profile]="profile | async"></app-profile>

Another way of doing it would be to use *ngIf with the 'as' syntax

<ng-container *ngIf="profile | async as p">
   <div> {{ p.username }}</div>
   <div> {{ p.email }}</div>
</ng-container>

Tags:

Angular