angular - 根据 *ngFor / *ngIf 中的值添加标题
问题描述
无法找到我的问题的解决方案,我在这里问我的问题。
我正在从我的数据库中检索对象列表。每个水果都包含以下值:ID、名称、图像、代码和颜色。
我想为每种水果颜色显示一个标题。
在我的示例中,我得到 2 个红色水果和 1 个蓝色水果。所以我想用下面的2个红色水果得到一个标题“RED”,下面有一个蓝色水果的标题“BLUE”。
这就是我设法做到的:
<div class="col-md-10 offset-md-1 row d-flex justify-content-center after-loop">
<div *ngFor="let fruit of fruits$;">
<div *ngIf="fruit.color == 'red'">
<h3 style="color:#fff"><span style="color:#ea4848">COLOR</span> - Red</h3>
<div *ngIf="active">
<app-fruit [name]="fruit.name" [image]="fruit.image" [code]="fruit.code"
[color]="fruit.color"></app-fruit>
</div>
</div>
</div>
</div>
如果水果是红色的,它会在水果卡片上方打印一个标题。我更多的是寻找一个“全球”的标题。
谢谢你的帮助。
解决方案
我建议reduce
首先根据它们的颜色对您的数组进行分组,然后在您的颜色数组上获取实例,以便我们能够在分组的水果中循环
已创建Stackblitz Demo供您参考
零件
// Group the fruits by their colors
this.groupedFruits = this.fruits
.reduce((box, fruit) => {
box[fruit.color] = box[fruit.color] ? [ ...box[fruit.color], fruit ] : [ fruit ];
return box;
}, {});
// Grab all the color keys inside your groupedFruits array
this.colors = Object.keys(this.groupedFruits);
分组时,您groupedFruits
的数据将如下所示:
{
red: [{ name: 'apple' }, { name: 'strawberry'}],
yellow: [{ name: 'mango' }],
...and so on
}
模板
<ul *ngFor="let color of colors">
// Color Name with count of how many fruits under that color
<h4 class="ml-0">
{{ color }}
<span class="badge badge-secondary">{{ groupedFruits[color].length }}</span>
</h4>
// loop the fruits according to their color
<li *ngFor="let fruit of groupedFruits[color]">{{ fruit.name }}</li>
</ul>
推荐阅读
- r - 如何执行引导程序以找到 R 中 k-nn 模型的置信区间?
- javascript - 在 node.js 应用程序中应该在哪里写 res.send()
- javascript - 如何等待按钮可点击
- python - 是否可以使用散景在 OSM 平铺图中显示比例?
- java - 无法识别并单击日期字段中的“下一步”按钮
- gnuplot - 在 gnuplot 上重绘 Excel 图形
- python - 带有 RandomizedSearchCV 的 XGBoost 分类器的precision_score 错误
- php - php 和 mysql 将空值填充为 empty
- python - 提高稀疏矩阵的幂
- asp.net-core - 带有 .net 5.0 框架的 Blazor 无法识别 razor 文件中的标记帮助程序