简体   繁体   中英

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

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.

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, eg in this case app-profile and to pass profile | async 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>

This is a bit hacky but I've seem a lot of examples using something like this:

<template ngFor let-profile [ngForOf]="profile$ | async">
  <div> {{ profile.username }}</div>
  <div> {{ profile.avatar }}</div>
  <div> {{ profile.email }}</div>
  ...
</template>

There is an alternative but it is more tedious. The solution that Günter Zöchbauer propsed mitigates that fact.

The alternative would be to subscribe to the observable inside of the component and then use the subscription variable in your template. You must unsubscribe the subscription in the OnDestroy event to prevent memory leaks. The async pipe do that for you. That is why the accepted solution is cleaner. But if you dont want to create a new component this is the way to go.

]f you want access to object on inner vm$ like this type vm$: Observable<{ profile: {} }> ;

try below snippet and don't forget ? mark.

<ng-container *ngIf="(vm$ | async)?.profile as profile">
  <div> {{ profile.username }}</div>
  <div> {{ profile.email }}</div>
</ng-container>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM