-1

I would like to present data - which is an Object in Angular Mat Table example below:

{
   "first": 15.0,
   "second": [{"id":1,"data_1":"foo","dat_2":"bar"}],
   "third": "2018-09-15T05:30",
   "fourth": ["ONE", "TWO"],
   "fifth": {"data_3":145,"id":2,"data_4":1600}
}

In fact I want to display it in a table, in first column there will be keys like "first", "second" and so on, in second column there will be a value (this might be a string, number array or array of objects.

What I actually have is presented here: my current progress - in table-basic-example.ts there are two elements: ELEMENT_DATA_NEW which is displayed correctly, however I want to display NEW_DATA

Note: I use angular mat dialog to open dialog, where this table will be presented.

Robert Głowacki
  • 292
  • 5
  • 22

2 Answers2

1

You need to convert the NEW_DATA to dataSouce:

dataSource = Object.entries(NEW_DATA).map(o => {
    return { name: o[0], value: JSON.stringify(o[1]) };
});

https://stackblitz.com/edit/angular-table-content-of-object-onx5sm

huan feng
  • 7,307
  • 2
  • 32
  • 56
  • Thanks a lot, however I had do change my way of displaying data due to the fact that it is rather useful for displaying database with large amount of records, rather than one record with several values connected with one record. – Robert Głowacki Jul 03 '20 at 15:20
1

You need to convert NEW_DATA to array. Simply do

dataSource = Object.entries(NEW_DATA); 

And also alter table template. Instead of name/value use indexes.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
 
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element[0]}} </td>
  </ng-container>
  
  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef> Value </th>
    <td mat-cell *matCellDef="let element"> {{element[1]}} </td>
  </ng-container>

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

https://stackblitz.com/edit/angular-table-content-of-object-5d19au