Display nested JSON data on Angular Material Table

Viewed 3560

The Json file has following format -

{
"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>
2 Answers

You need to make the JSON into a variable like,

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,

dataSource = jsonData.products.items;

And sisplay columns with properties like,

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

And HTML template refering these properties,

<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

The dataSource must be an array (in your case is products['items']).

Related