[Fixed] How do I add rows to the dynamic material table in angular with array of rows

Issue

I am trying to create a material table with data of dynamic headers and rows which is an array of array of strings. But I am not able to get rows inside the table

https://stackblitz.com/edit/angular-ivy-j5prjg?file=src%2Fapp%2Fapp.component.html

<div *ngIf="customerResponse">
  <mat-table [dataSource]="customerResponse.customerDataRows">
    <ng-container *ngFor="let disCol of customerResponse.customerHeader; let colIndex = index"
      matColumnDef="{{ disCol }}">
      <th mat-header-cell *matHeaderCellDef>{{ disCol }}</th>
      <ng-container *ngFor="let disRow of customerResponse.customerDataRows;">
        <td mat-cell *matCellDef="">{{disRow}}</td>
      </ng-container>
    </ng-container>
    <mat-header-row *matHeaderRowDef="customerResponse.customerHeader; "></mat-header-row>
    <mat-row *matRowDef="let row; columns: customerResponse.customerHeader"></mat-row>
  </mat-table>
</div>

Right now, I can show the headers that I get from the ts file but I need help in getting the rows data inside the mat cell

Solution

I’ve made some modifications to your code.

At the Mat Cell Definition, I changed your code from:

<ng-container *ngFor="let disRow of customerResponse.customerDataRows;">
    <td mat-cell *matCellDef="">{{disRow}}</td>
</ng-container>

to:

<td mat-cell *matCellDef="let disRow">{{disRow[colIndex]}}</td>

The definition of *matCellDef was empty. Also, as the array of data relies on the position of the data, I used colIndex as the key to find the row data, but I prefer using key/value pair because they are less error prone: if a column of customerHeader is not part of the displayed columns, the row’s cells may not match the correct column.

I’ve made this fork of your stackblitz code with the modifications: https://stackblitz.com/edit/angular-ivy-2ngiqh?file=src/app/app.component.html

Leave a Reply

(*) Required, Your email will not be published