Home > Software design >  How present JSON List in Angular HTML with *ngFor
How present JSON List in Angular HTML with *ngFor

Time:01-08

I get a result in the JSON Format like these sample from a webservice. How can i iterate over this items to prensent the objects

HTML Code - not working

<div *ngFor="let item of List">
  {{item.Code}}
</div>

JSON Sample

"List": {
  "0": {
         "Code": "A"
       },
  "1": {
         "Code": "B"
       },
  "2": {
         "Code": "C",
       }
  }

unfortunally the webservice does not provide this as an Array [] of objects

I want to see the list of all items für the Key "Code"

CodePudding user response:

You can use KeyValuePipe like here.

So the your code would be something like this:

<div *ngFor="let item of List | keyvalue">
  {{item.value.Code}}
</div>

CodePudding user response:

As it was not working with

<div *ngFor="let item of List | keyvalue">
  {{item.value.Code}}
</div>

Typescript was throwing an error because {{item.value.Code}} was not known.

I did some additional research and found the following solution

<div *ngFor='let key of objectKeys(List)'>
  {{List[key].Code}} 
</div>

in the typescript class corresponding to the html file you have to add

objectKeys = Object.keys;
  • Related