当Angular中的数组为空时,我如何消失垫卡?
这是我的 Angular HTML 文件代码:
<mat-card *ngFor="let getCartDetail of getCartDetails" >
<div>
<mat-card-title ><h3>{{getCartDetail.title1}}</h3> </mat-card-title>
</div>
</mat-card>
当“getCartDetails”数组为空时,出现错误“无法读取未定义的属性‘title1’”。我如何将空字符串设置为 getCartDetail.title1 或者我可以在数组为空时将其消失。
回答
有多种方法
选项 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