Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

my template have something like...

<div> {{ (profile$ | async).username}}</div>
<div> {{ (profile$ | async).email}}</div>

Is there a way to assign (profile | async) to a local variable? having to type it out for every single field is bad for readability.

Thanks.

like image 297
jho Avatar asked Sep 25 '16 01:09

jho


Video Answer


2 Answers

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.

like image 104
Frederik Aalund Avatar answered Oct 19 '22 15:10

Frederik Aalund


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>
like image 29
Alexander Ciesielski Avatar answered Oct 19 '22 15:10

Alexander Ciesielski