Отображать вложенные JSON данные на Angular Таблица материалов - PullRequest
0 голосов
/ 10 марта 2020

Файл Json имеет следующий формат -

{
"products": {

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

Предполагается, что он отображается в таблице материалов. Я вижу, что данные прошли, как показано в консоли, но не видны в материале. стол.

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

0 голосов
/ 10 марта 2020

Вам необходимо преобразовать JSON в переменную типа

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

Затем datasource необходимо объявить с массивом items как,

dataSource = jsonData.products.items;

И столбцы sisplay с такими свойствами, как

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

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

Рабочий материал таблицы Stackblitz

0 голосов
/ 10 марта 2020

dataSource должен быть массивом (в вашем случае это products['items']).

...