在 angular 9 中使用 *ngFor 显示键和数组值

Display key and array values using *ngFor in angular 9

JSON

{
 "cars":
{
  "12345": [1960, 1961, 1962],
  "4567": [2001, 2002]
}
}

HTML

<strong>Plate and year</strong>
<div *ngFor="let list of lists">
{{list.cars}}
</div>

我需要这样显示:

车牌和年份

12345- 1960, 1961, 1962.

4567- 2001, 2002.

根据您的数据结构,您可以使用 KeyValuePipe 和额外的嵌套 *ngFor 来实现此目的。 KeyValuePipe 允许您迭代类似于 Object.entries 的对象,为每个项目提供 keyvalue 属性。在这种情况下,value 将是一个数组,您可以使用 *ngFor:

对其进行迭代
<strong>Plate and year</strong>
<div *ngFor="let list of lists">
  <div *ngFor="let car of list.cars | keyvalue">
    <div>{{car.key}} - <div *ngFor="let year of car.value">{{year}}</div>
    </div>
  </div>
</div>

这是一个 example 的动作。

希望对您有所帮助!