首页 > 解决方案 > 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 返回数据,它不应该。任何想法为什么会发生这种情况以及我应该如何解决这个问题?

标签: angulartemplatesif-statementconditional-statements

解决方案


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.


推荐阅读