【问题标题】:listing items with ngFor and ngIf at the same time同时使用 ngFor 和 ngIf 列出项目
【发布时间】:2019-01-26 12:34:11
【问题描述】:
我想用 ngFor 创建卡片,但我也想用 ngIf。因此,如果数组为空,则必须显示一张卡片,上面写着“没有标题!”如果数组包含一些值,那么卡片必须显示数组的值。
<mat-card class="asd cardPardding" *ngFor="let title of titles">
<p>
{{title}}
</p>
</mat-card>
但如果我将 ngIf 包含到
中,则使用此代码会列出数组项
然后 ngFor 禁用卡片项目,所以它没有意义。
我该怎么做?
【问题讨论】:
标签:
angular
angular-material
【解决方案1】:
使用 Angular 容器和模板:
<ng-container *ngIf="titles?.length; else noTitle">
<mat-card class="asd cardPardding" *ngFor="let title of titles">
<p>
{{title}}
</p>
</mat-card>
</ng-container>
<ng-template #noTitle>
<mat-card class="asd cardPardding">
<p>
No title !
</p>
</mat-card>
</ng-template>