Anand Srivastava
Anand Srivastava

Reputation: 71

Creating Dynamic Angular Material table from JSON data

Would like to know if it is possible to create a dynamic Material table from JSON data. The amount of columns and headers should change according to the keys in the JSON. For example this JSON should create this table:

{
     color: "green", code: "#JSH810"
}
,
{
     color: "red", code: "#HF59LD"
}
        Color          Code

        green         #JSH810
        red           #HF59LD

And this JSON should create this table:

{
    id: "1", type: "bus", make: "VW", color: "white"
}

,
{
    id: "2", type: "taxi", make: "BMW", color: "blue"
}

      id     type      make     color

      1      bus       VM        white
      2      taxi      BMW       blue

It should be a material table , i know how to achieve this in HTML table using ngFor

    <table>
      <thead>
        <tr>           
          <th *ngFor="let head of items[0] | keys">{{head}}</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of items">           
          <td *ngFor="let list of item | keys">{{item[list]}}</td>
        </tr>
      </tbody>
    </table>

Can anyone help me in converting this to a material table ?

Upvotes: 2

Views: 3730

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24414

this an example base of the angular material table example you can check it here

the table required two thing displayedColumns list and data source ,

  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;

and for the template

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

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

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

I use ngFor to setup the deader sections and an example you will get the data source from api request , you can get the columns key by get the key of any object from the respond by Object.keys method

export class TableBasicExample {
  displayedColumns: string[];
  dataSource :any[];

  ngOnInit(){
    // http request to get the data 
    this.dataSource = ELEMENT_DATA
    this.displayedColumns= Object.keys(ELEMENT_DATA[0])
  }
}

demo 🌠

Upvotes: 4

Related Questions