john
john

Reputation: 707

How to create a mat angular table from JSON string?

I have an input JSON string from server. It can have any number of columns. I want to be able to create MAT angular table from this JSON. This is my test environment https://stackblitz.com/edit/angular-wcjorj

Currently, I'm hard coding all column names in the html page. For each column I use ng-container like this:

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

But I need to be able to do this dynamically, for any other JSON data table. How can I create that html table dynamically? I tried to use ngFor, however, it got very messy and I wasn't able to make it work

Upvotes: 0

Views: 455

Answers (1)

indrajeet
indrajeet

Reputation: 897

once you get the data from server check if array is not empty then take the first object from array and create a columns array from object keys.

this is in your componenet

if (this.inputData.length > 1) {
this.displayedColumns: string[] = Object.keys(this.inputData[0]);
}

then in your html you will be looping through displayedColumns

<ng-container matColumnDef="{{col}}" *ngFor="let col of displayedColumns ">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> {{col}}
      </th>
      <td mat-cell *matCellDef="let element" >
         {{element[col]}}
      </td>
    </ng-container>

Upvotes: 2

Related Questions