Angular ngIf在评估条件之前显示else模板

问题描述 投票:1回答:2

在显示之前我正在检查数组中是否有任何元素。如果没有,则应显示“不可用”消息。

类:

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返回的,而不是。任何想法为什么会发生这种情况,我该如何解决这个问题?

angular templates if-statement condition ngif
2个回答
3
投票

发生这种情况是因为你的if子句基于lists数组的长度,该数组的初始值为空数组。

更新逻辑以包含isLoading将有助于此特定方案。

<div *ngIf="isLoading || lists.length > 0; then withLists else withoutLists"></div>

根据下面的评论,更好的方法可能是做更多的事情:

<ng-component *ngIf="!isLoading">
   <div *ngIf="lists.length > 0; then withLists else withoutLists"></div>
</ng-component>

这样,代码的意图就会更清晰。如果仍在加载,请不要显示任何内容。否则,根据列表的长度显示带有if / else逻辑的diff。


0
投票

subscribe中的回调是异步的,这意味着在加载数据时列表为空,因此您需要等待加载完成。你可以通过以下方式解决这个问题:

<div *ngIf="isLoading || lists.length > 0; then withLists else withoutLists"></div>

或包装这样的一切:

<div *ngIf="isLoading">
    <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>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.