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

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

问题描述

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

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

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

<ng-container *ngIf="users.length > 1">...</ng-容器>

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

解决方案

您可以这样做:

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

请记住,当使用来自 http 请求的订阅时,这会触发请求两次.所以你应该使用一些状态管理模式或库来避免这种情况发生.

这是一个stackblitz.

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>

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.

解决方案

You can do this:

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

Keep in mind that when using a subscription from a http-request, this would trigger the request twice. So you should use some state-management pattern or library, to not make that happen.

Here is a stackblitz.

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

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