angular - 当 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 设置一个空字符串,或者我可以在数组为空时消失。
解决方案
有多种方法
选项 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
推荐阅读
- java - 表中键数的准确范围
- javascript - js中的两个for循环。无法在嵌套的 for 循环上工作
- javascript - Angular 2:滚动动画
- guidewire - 如何在 Guidewire 中安装 DCEVM?
- r - 移动 geom_label 的框,使它们不重叠
- elasticsearch - 在 Elasticsearch 中更改设置的最佳解决方案
- javascript - 正则表达式不允许没有前缀或后缀的特殊字符
- reactjs - 为什么 React-Scroll activeClass 不起作用?
- python - 如何删除隐藏的 utdated scipy 文件,使其不会在 VS Code OSX 中使用 python 导入
- mysql - Mysql 语句有语法问题