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 .