简体   繁体   中英

How present JSON List in Angular HTML with *ngFor

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"

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>

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM