Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/39682546/local-variable-in-template-for-async-pipe-angular-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...