具有异步管道多个条件的 Angular *ngIf 变量

2024-05-08

有一个关于在 Angular 中使用 *ngIf 的很好的文档:https://angular.io/api/common/NgIf https://angular.io/api/common/NgIf但是,是否可以有 *ngIf 异步变量并对其进行多次检查? 就像是:

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

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

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

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


你可以这样做:

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

请记住,当使用来自 http 请求的订阅时,这将触发请求两次。因此,您应该使用某种状态管理模式或库,以避免这种情况发生。

这里有一个堆栈闪电战 https://stackblitz.com/edit/obs-with-ngif-ngfor.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有异步管道多个条件的 Angular *ngIf 变量 的相关文章

随机推荐