异步管道模板中的局部变量(角度2+)

jho*_*jho 32 angular

我的模板有......

<div> {{ (profile$ | async).username}}</div>
<div> {{ (profile$ | async).email}}</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法将(profile | async)分配给局部变量?必须为每个字段输入它都不利于可读性.

谢谢.

Fre*_*und 47

从Angular 4.0.0-rc.1(2017-02-24)开始,您可以使用增强*ngIf语法.这是让你*ngIf在模板局部变量中分配条件的结果:

<div *ngIf="profile$ | async as profile">
    <div>{{profile.username}}</div>
    <div>{{profile.email}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

更新的*ngIf文档进一步详细说明,并提供了许多使用async*ngIf一起使用的好例子.

一定要查看then和的else陈述*ngIf.

Cory Rolan做了一个简短的教程,你可以在5-10分钟内消化.


Ale*_*ski 11

最好的方法是创建一个新组件,例如在这种情况下app-profile并传递profile | async给该组件.在组件内部,您可以根据需要为变量命名.

<app-profile [profile]="profile | async"></app-profile>
Run Code Online (Sandbox Code Playgroud)