angular - Angular 的 ngIf 在评估条件之前显示 else 模板
问题描述
在显示它们之前,我正在检查数组中是否有任何元素。如果没有,则应显示“不可用”消息。
班级:
public lists = [];
public isLoading: boolean = false;
ngOnInit() {
this.getLists()
}
getLists() {
this.isLoading = true;
this.list.getShoppingLists().subscribe(data => {
this.isLoading = false;
this.lists = data.data;
});
}
模板:
<mat-spinner *ngIf="isLoading" class="mx-auto"></mat-spinner>
<div *ngIf="lists.length > 0; then withLists else withoutLists"></div>
<ng-template #withLists>
<div *ngFor="let list of lists">
<p>{{list.title}}</p>
</div>
</ng-template>
<ng-template #withoutLists>
<p>No lists available</p>
</ng-template>
我遇到的问题是模板中显示“不可用”消息,同时从 API 返回数据,它不应该。任何想法为什么会发生这种情况以及我应该如何解决这个问题?
解决方案
This is happening because your if clause is based on the length of the lists
array which is given an initial value of an empty array.
Updating the logic to include isLoading
would help for this specific scenario.
<div *ngIf="isLoading || lists.length > 0; then withLists else withoutLists"></div>
As per the comments below, a better approach might be to do something more like:
<ng-component *ngIf="!isLoading">
<div *ngIf="lists.length > 0; then withLists else withoutLists"></div>
</ng-component>
This way, the intent of the code would be more clear. If it is still loading, don't show anything. Else show the diff with the if/else logic based on the length of lists.
推荐阅读
- php - 将 laravel 项目从 live 迁移到 local
- c++ - 在恒定时间内访问 QGraphicsScene 中的 QGraphicsItems?
- excel - 更改反斜杠之间部分字符串的颜色
- arraylist - 如何在方法中保存 ArrayList 状态?
- oracle - 使用 Vertabelo 中生成的 SQL 代码创建表时缺少右括号错误
- javascript - PapaParse CSV 到 JSON - 未调用 transformHeader 回调
- oracle - 将 codeigniter 连接到数据库 oracle 服务器
- html - 旋转里面的文字,但不允许增加 ?
- c - 当数字在数字中显示两次时打开标志 - C
- javascript - Node.js 使用 Bcrypt 库登录