简体   繁体   English

在 Angular Material Table 上显示嵌套的 JSON 数据

[英]Display nested JSON data on Angular Material Table

The Json file has following format - Json 文件具有以下格式 -

{
"products": {

    "items":[
      {
        "productId": "1",
        "dept": "home",
        "itemtype": "small"
      },
      {
       "productId": "2",
        "dept": "kitchen",
        "itemtype": "medium"
      }
       ] }}

This is suppose to display on a material table, I can see the data has passed as shows in the console, but not visible in the material table.这假设显示在材料表上,我可以在控制台中看到数据已通过,但在材料表中不可见。

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" >
<ng-container matColumnDef="productId" >
   <th mat-header-cell *matHeaderCellDef> ID</th>
    <td mat-cell *matCellDef="let element ">{{element.productId}}  
   </td>
 </ng-container>
<ng-container matColumnDef="dept" >
   <th mat-header-cell *matHeaderCellDef> department</th>
    <td mat-cell *matCellDef="let element ">{{element.dept}}  
   </td>
 </ng-container>
 <ng-container matColumnDef="itemtype" >
   <th mat-header-cell *matHeaderCellDef> Item type</th>
    <td mat-cell *matCellDef="let element ">{{element.itemtype}}  
   </td>
 </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
 <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

You need to make the JSON into a variable like,您需要将JSON变成一个变量,例如,

const jsonData = {
"products": {
    "items":[
      {
        "productId": "1",
        "dept": "home",
        "itemtype": "small"
      },
      {
       "productId": "2",
        "dept": "kitchen",
        "itemtype": "medium"
      }
    ] 
  }
}

Then the datasource needs to be declared with array items like,然后需要使用数组items声明datasource ,例如,

dataSource = jsonData.products.items;

And sisplay columns with properties like,以及具有以下属性的 sisplay 列,

  displayedColumns = ['productId', 'dept', 'itemtype'];

And HTML template refering these properties,和引用这些属性的HTML模板,

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="productId">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let element"> {{element.productId}} </td>
  </ng-container>

  <ng-container matColumnDef="dept">
    <th mat-header-cell *matHeaderCellDef> department </th>
    <td mat-cell *matCellDef="let element"> {{element.dept}} </td>
  </ng-container>

  <ng-container matColumnDef="itemtype">
    <th mat-header-cell *matHeaderCellDef> Item type </th>
    <td mat-cell *matCellDef="let element"> {{element.itemtype}} </td>
  </ng-container>


  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Working material table Stackblitz工作材料表 Stackblitz

dataSource必须是一个数组(在您的情况下是products['items'] )。

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

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