Angular 4 Primeng 4数据表 - 加载嵌套json

时间:2017-05-25 03:17:04

标签: angular datatable primeng

我正在尝试将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>

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

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

     <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>
    

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

    我希望这有帮助!