首页 > 解决方案 > 当 Angular 中的数组为空时,我如何消失垫卡?

问题描述

这是我的 Angular HTML 文件代码:

<mat-card  *ngFor="let getCartDetail of getCartDetails"  style="margin-bottom: 1em; " >
            <div class="card-container"> 
                <mat-card-title ><h3>{{getCartDetail.title1}}</h3> </mat-card-title>
            </div>
    </mat-card>

当“getCartDetails”数组为空时,出现错误“无法读取未定义的属性 'title1'”。我如何为 getCartDetail.title1 设置一个空字符串,或者我可以在数组为空时消失。

标签: angulartypescript

解决方案


有多种方法

选项 1:使用*ngIf

您可以在使用之前检查数组是否已定义。由于单个元素不能有两个结构指令,因此我将其包装在<ng-container>.

<ng-container *ngIf="!!getCartDetails && getCartDetails.length">
  <mat-card  *ngFor="let getCartDetail of getCartDetails"  style="margin-bottom: 1em; " >
    <div class="card-container"> 
      <mat-card-title><h3>{{getCartDetail.title1}}</h3> </mat-card-title>
    </div>
  </mat-card>
</ng-container>
  • !!getCartDetails检查变量getCartDetails是否已定义。在这里查看更多关于 double-bang 的信息!!
  • getCartDetails.length检查数组是否为空

当条件失败时,这里<mat-card>不会呈现。

选项 2:安全导航操作员?.

您可以使用安全导航运算符?.在访问变量的属性之前检查变量是否已定义。

<mat-card  *ngFor="let getCartDetail of getCartDetails"  style="margin-bottom: 1em; " >
  <div class="card-container"> 
    <mat-card-title><h3>{{getCartDetail?.title1}}</h3> </mat-card-title>
  </div>
</mat-card>

当不可用时,此处<mat-card>将呈现为空。<mat-card-title>title1

选项 3:使用||

Angular 模板插值中的语句{{ }}是有效的 Typescript 表达式,因此您可以||在表达式失败时使用替代值。

<mat-card  *ngFor="let getCartDetail of getCartDetails"  style="margin-bottom: 1em; " >
  <div class="card-container"> 
    <mat-card-title><h3>{{ getCartDetail.title1 || '' }}</h3> </mat-card-title>
  </div>
</mat-card>

当不可用时,此处<mat-card>将呈现为空。<mat-card-title>title1


推荐阅读