2
votes

I am getting issue in Angular material table with dynamic table content and header. Here is my JSON data for table.

let dataobj=[
  [
{
  "key": "Data1",
  "value": "ENF"
},
{
  "key": "Data2",
  "value": "10598489700"
},
{
  "key": "Data3",
  "value": "3662946630"
},
{
  "key": "Comments",
  "value": ""
},
{
  "key": "Readonly",
  "value": "true",
  "index": 0
}
],
[
{
  "key": "Data1",
  "value": "FNS"
},
{
  "key": "Data2",
  "value": "10598489700"
},
{
  "key": "Data3",
  "value": "3662946630"
},
{
  "key": "Comments",
  "value": ""
},
{
  "key": "Readonly",
  "value": "true",
  "index": 1
}
]

]

Here is the code for creating the displayColumnHeader Array value

this.displayColumnHeader = Object.keys(dataobj[0]).map(key => (key));

Below code for passing the value to datatable

this.dataSource = new MatTableDataSource<Element>(dataobj);

Please find the below code for template and bindings

 <div class="row">
    <div class="col-lg-12">
        <div class="example-container">
        <mat-table #table [dataSource]="dataSource">

          <!-- please check the below code section for this part -->

            <mat-header-row *matHeaderRowDef="let header; displayColumnHeader"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayColumnHeader;"></mat-row>
        </mat-table>
        <mat-paginator #paginator [pageSize]="10" [pageSizeOptions]="[5, 10, 20]">
        </mat-paginator>
        </div>
    </div>
</div>

Below code section for row and column cell mapping. The below section is I am struggle to map the value for header cell and data cell. Because i don't know the property name when creating the template. it's dynamic.

<ng-container *ngIf="row.key.indexOf('Readonly')<0 && row.key.toUpperCase().indexOf('COMMENTS')<0">
                <ng-container>
        <mat-header-cell *matHeaderCellDef>{{row.key}}</mat-header-cell>
         <mat-cell *matCellDef="let element"> {{element.value}} </mat-cell>
                </ng-container>
  </ng-container>
1
gosh, I have the same issue but I'm so disappointed that nobody answered to this! Did you find a solution? I am totally getting crazy around thisNad G

1 Answers

0
votes

Assuming tabledata contains all the rows of the table and displayColumnHeader contians headers of the table whose values are dynamic i.e known at run time only.

Below lines defines the datasource and sets the header of the material table.

 <mat-table #table [dataSource]="tabledata" class="mat-elevation-z8" matSort>
 <ng-container *ngFor="let header of displayColumnHeader;let i=index; " [matColumnDef]="header">
     <th mat-header-cell *matHeaderCellDef mat-sort-header> {{header}}
      </th>

Below code maps each row cell to a particular header,such like column being key and value being each row cell value

<tr mat-header-row *matHeaderRowDef="displayColumnHeader"></tr>
<tr mat-row *matRowDef="let row; columns: displayColumnHeader; let i = index; let even = even;">
</tr>