首页 文章

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

提问于
浏览
5

在Angular中使用* 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>

但是只使用一个容器而不是两个容器真的很好 .

2 回答

  • 0

    简单地这样做吧

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

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

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

    Edit: 上一个不起作用,因为你不能在不使用ng-template的情况下使用 *ngFor*ngIf . 你会这样做的

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

    这是stackblitz .

  • 4

    我遇到了需要带有多个检查的* ngIf异步变量的相同问题 .

    这最终对我有用 .

    <div *ngIf="(users$ | async)?.length > 0 && (users$ | async) as users"> ... </div>
    

    或者如果你愿意的话

    <div *ngIf="(users$ | async)?.length > 0 && (users$ | async); let users"> ... </div>
    

    Explanation

    由于if表达式的结果已分配给您指定的局部变量,因此只需使用 ... && (users$ | async) as users 结束检查,即可指定多个条件,并指定在所有条件成功时希望局部变量保持的值 .

    Note

    我最初担心在同一个表达式中使用多个 async 管道可能会创建多个订阅,但经过一些轻量级测试(我可能是错误的)之后,似乎实际上只有一个订阅 .

相关问题