Angular * ngIf变量具有异步管道的多个条件 [英] Angular *ngIf variable with async pipe multiple conditions

查看:490
本文介绍了Angular * ngIf变量具有异步管道的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular中使用* ngIf的文档非常好: https://angular.io/api/common/NgIf 但是,是否可能有* ngIf异步变量并对此进行多次检查? 像这样:

There's quite good doc of using *ngIf in Angular: https://angular.io/api/common/NgIf But, is that possible to have *ngIf async variable and multiple checks on that? Something like:

<div *ngIf="users$ | async as users && users.length > 1">
...
</div>

当然,可以使用嵌套的* ngIf,例如:

Of course, it's possible to use nested *ngIf, like:

<div *ngIf="users$ | async as users">
    <ng-container *ngIf="users.length > 1">
    ...
    </ng-container>
</div>

但是最好只使用一个容器,而不是两个.

but it'd be really nice to use only one container, not two.

推荐答案

只需这样做

<div *ngfor="let user of users$ | async" *ngIf="(users$ | async)?.length > 1">...</div>

对于更复杂"的情况,请执行以下操作

For "more complex" scenario do the following

<div  *ngfor="let user of users$ | async" *ngIf="(users$ | async)?.length > 1 && (users$ | async)?.length < 5">...</div>

上一个将不起作用,因为如果不使用*ngFor和*ngIf ="noreferrer"> ng-template .例如,您会这样做

Previous wouldn't work since you cannot use *ngFor and *ngIf without using ng-template. You would do it like that for instance

<ng-template ngFor let-user [ngForOf]="users$ | async" *ngIf="(users$ | async)?.length > 1 && (users$ | async)?.length < 5">
  <div>{{ user | json }}</div>
</ng-template>

这是 stackblitz .

这篇关于Angular * ngIf变量具有异步管道的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆