首页 > 解决方案 > 根据 *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>

我的结果

如果水果是红色的,它会在水果卡片上方打印一个标题。我更多的是寻找一个“全球”的标题。

谢谢你的帮助。

标签: angular

解决方案


我建议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>

推荐阅读