-2

I am having this object:

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

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

How can I iterate through this project in my component Tempate? I tried:

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

In a project that I use Angular 8, keyValue pipeline worked. What can I do here? I am using "target": "es2015".

Kathrine Hanson
  • 575
  • 2
  • 10
  • 32

2 Answers2

2

You are looking for KeyValuePipe, see the detail

Use the same object as you have:

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

Then your 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>
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
1

You can also use the keys of your object to loop through:

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>
Michael Yimam
  • 131
  • 1
  • 3