简体   繁体   English

如何在 Angular HTML 中使用 *ngFor 显示 JSON 列表

[英]How present JSON List in Angular HTML with *ngFor

I get a result in the JSON Format like these sample from a webservice.我从 web 服务中得到了 JSON 格式的结果,就像这些示例一样。 How can i iterate over this items to prensent the objects我如何遍历这些项目来呈现对象

HTML Code - not working HTML 代码 - 不工作

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

JSON Sample JSON样品

"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 .您可以像这里一样使用 KeyValuePipe。

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. Typescript 抛出错误,因为 {{item.value.Code}} 未知。

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在typescript class对应的html文件中你要加上

objectKeys = Object.keys;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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