遍历 Angular 中的对象键 5

Iterate through object key in Angular 5

我有这个对象:

protected products: { 
 [key: string]: {
  color: string,
  brand: string,
 };
} = {};

products =  {
 scan12345: {color: "Orange", brand: "X"},
 scan13813: {color: "Pink", brand: "X"},
}

如何在我的组件模板中迭代这个项目?我试过了:

<ion-item *ngFor="let pro of products">
   {{ pro.color }}
</ion-item>

在我使用的项目中 Angular 8,keyValue 管道有效。我可以在这里做什么? 我正在使用 "target": "es2015".

您还可以使用对象的键循环:

products =  {
  scan12345: {color: "Orange", brand: "X"},
  scan13813: {color: "Pink", brand: "X"},
}
this.productKeys = Object.keys(products);
<ion-item *ngFor="let key of productKeys">
   {{ products[key].color }}
</ion-item>

您正在寻找KeyValuePipe,查看详情

使用与您相同的对象:

products =  {
  scan12345: {color: "Orange", brand: "X"},
  scan13813: {color: "Pink", brand: "X"},
}

那么你的HTML:

<div *ngFor="let item of products | keyvalue">
      Single Object: {{item.key}}:{{item.value}} <br>
      Color: {{item.value.color}} <br>
      Brand: {{item.value.brand}}
</div>