【问题标题】:Angular 4 Primeng 4 datatable - Loading nested jsonAngular 4 Primeng 4 数据表 - 加载嵌套的 json
【发布时间】:2017-05-25 03:17:03
【问题描述】:

我正在尝试将下面的 json 加载到primeng数据表中。我在设置列名时遇到问题

[
  {
    "accountId": 1,
    "accountName": "Environmental Service Ltd",
    "addressBook": {
      "addressBookId": 1,
      "companyId": 1,
      "addressList": [
        {
          "addressLine1": "ABC",
          "addressLine2": "XYZ",
          "addressLine3": "TUV",
          "city": "ALY",
          "postCode": "AB9 7RT"
        }
      ]
    }
  }
]

我的代码在这里

<p-dataTable #dtAccounts [value]="accounts">
  <p-header>Accounts</p-header>
  <p-column field="accountName" header="Account Name" [sortable]="true"></p-column>
  <p-column field="telephone" header="Account Phone" [sortable]="true"></p-column>
  <p-column field="addressLine1" header="Street"></p-column>
  <p-column field="city" header="City"></p-column>
  <p-column field="state" header="State/Province"></p-column>
  <p-column field="postCode" header="Zip/Postal Code"/>
</p-dataTable>

【问题讨论】:

  • 您面临的具体问题是什么?您是指“accountName”列吗?
  • 这是错误的:&lt;p-column field="postCode" header="Zip/Postal Code"/&gt;,应该是:&lt;p-column field="postCode" header="Zip/Postal Code"&gt;&lt;/p-column&gt; 但它仍然只会根据 JSON 的样子填充表中的 accountName

标签: angular datatable primeng


【解决方案1】:

您的代码有一些问题:

  1. 数据模型与列定义不匹配:
    • “电话”字段在数据模型中不存在
    • 数据模型中不存在“state”字段
    • “addressLine1”、“city”、“postcode”不适合数据模型(它们位于嵌套“addressBook”对象的“addressList”数组中。每个“addressList”数组都有具有这些属性的嵌套对象)
    • &lt;p-column field="postCode" header="Zip/Postal Code"/&gt; 组件标签不能自动关闭。使用&lt;/p-column&gt; to close &lt;p-column ...&gt;

这应该可行:

 <p-dataTable #dtAccounts [value]="accounts">
      <p-header>Accounts</p-header>
      <p-column field="accountName" header="Account Name" [sortable]="true"></p-column>
  </p-dataTable>

为了呈现嵌套地址列表,您可以使用模板列,如下所示:

<p-dataTable #dtAccounts [value]="accounts" tableStyleClass="table table-hover table-striped">
                <p-header>Accounts</p-header>
                <p-column field="accountName" header="Account Name" [sortable]="true"></p-column>
                <p-column field="addressList" header="Address List">
                    <ng-template let-account="rowData" pTemplate="body">
                        <ul>
                            <li *ngFor="let address of account.addressBook.addressList">
                               {{address.addressLine1}} - {{address.addressLine2}} - {{address.city}}- {{address.postCode}}
                            </li>
                        </ul>
                    </ng-template>
                </p-column>
            </p-dataTable>

或者您可以考虑使用最适合您的场景的其他组件,例如primeng/treetable

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 2018-03-24
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2018-06-02
    • 2018-04-15
    相关资源
    最近更新 更多