【问题标题】:How to display the table from nested json array in angular?如何以角度显示嵌套json数组中的表格?
【发布时间】:2019-08-20 05:49:49
【问题描述】:

我正在使用 Angular 7,我想在表格中显示嵌套的 json 数据。 我的 Json 结构:

{
  "id": "1",
  "referenceNumber": "P123",
  "supplierNote": "My Notes",
  "internalNote": "Your notes",
  "purchaseOrderProducts": [
   {
      "purchaseId": "p1",
      "quantity": 1000,
   },
   {
      "purchaseId": "p2",
      "quantity": 500,
   }
 ]
}

我想使用角度在表格中显示值“purchaseId”和“quantity”。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 在 我用了 let 方法(*ngFor="let item of PurchaseOrderForm.get('purchaseOrderProducts').controls; let i = index [formGroupName]="i") 我打电话 中的值使用 formControlName。但仅显示第一个组(“purchaseId”:“p1”)。不显示其他组。
  • 你能分享你的代码吗
  • @AngelReji 添加了带有工作示例的答案 hop 它有帮助:)

标签: angular angular6 angular5 angular7


【解决方案1】:
Use *ngFor in the html for the above
assuming the above json is an Object purchase

<table>
<div *ngFor="let obj of purchase.purchaseOrderProducts">
<tr>{{obj.purchaseId}}</tr>
<tr>{{obj.quantity}}</tr>
</div>
</table>

【讨论】:

  • 面对问题“无法读取未定义的属性'purchaseOrderProducts'”
  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。
【解决方案2】:

如果您只想显示purchaseidquantity 信息,则可以使用*ngFor 指令循环遍历purchaseOrderProducts 数组并显示数据。

HTML 如下所示:

<table bordar="2">
    <tr>
        <th>purchaseId</th>
        <th>quantity</th>
    </tr>
    <tr *ngFor="let data of arrObj?.purchaseOrderProducts">
        <td>    {{data.purchaseId}}</td>
        <td>{{data.quantity}}</td>
    </tr>
</table>

这是工作示例:

https://stackblitz.com/edit/angular-dfsfpr

【讨论】:

  • 谢谢。但是如何在表中使用 formControlName 绑定值呢?
  • 你想与 formControl 绑定的那些值?
  • 你必须使用formArray
  • "
    " 我用这种方式..但无法显示所有的价值观。请帮我解决这个问题
猜你喜欢
相关资源
最近更新 更多
热门标签