简体   繁体   English

使用ngIf定义了Check元素并且长度非零

[英]Check element is both defined and has a non zero length using ngIf

In an Angular app we retrieve via a service call a list of users. 在Angular应用程序中,我们通过服务调用检索用户列表。 If the user list is empty, we store in our state store an empty array [] . 如果用户列表为空,我们将在状态存储中存储一个空数组[]

In the component we want to display the user list. 在组件中我们要显示用户列表。 We use the async pipe. 我们使用异步管道。 We don't want to display the user list if the async call is not completed or fails, and if the length of user list is zero. 如果异步调用未完成或失败,并且用户列表的长度为零,我们不希望显示用户列表。

Here is the component html code at the moment: 这是目前的组件html代码:

<ng-container *ngIf="users$ | async as users">
  <ul *ngIf="users.length > 0">
    <li *ngFor="let user of users">{{user.name}}</li>
  </ul>
</ng-container>

Is there any way to combine the two ngIf checks in one statement. 有没有办法在一个语句中组合两个ngIf检查。 It appears to be a problem since we need to use the value users defined firstly using as keyword. 这似乎是一个问题,因为我们需要首先使用users定义的值as关键字。

Something like: 就像是:

*ngIf="users$ | async as users && users.length > 0" doesn't work. *ngIf="users$ | async as users && users.length > 0"不起作用。

In issue #15481 on Angular GitHub, the question was asked about the as syntax: 在Angular GitHub上的问题#15481中 ,有人问到了as语法:

Can I use "as" in ngIf statement and get its property as a condition to ngIf? 我可以在ngIf语句中使用“as”并将其属性作为ngIf的条件吗?

The answer given by Dzmitry Shylovich was: Dzmitry Shylovich给出的答案是:

Nope


One way of condensing it in a single ngIf condition was suggested by Arlo White in issue #16173 : mapping the value to null if the list is empty. Arlo White在问题#16173中提出了在单个ngIf条件下对其进行压缩的一种方法:如果列表为空,则将值映射为null That method is shown in this stackblitz . 该方法显示在此stackblitz中

<ng-container *ngIf="users$ | async as users">
this.users$ = usersObservable.map(x => x.length > 0 ? x : null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM