0

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

1
  • Yes, the option is to use ngFor and you can get source for ngFor also from a function. Commented Jun 28, 2019 at 20:36

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.