Mat table with ngFor and sorting

Avihay m picture Avihay m · Jul 15, 2018 · Viewed 16.9k times · Source

I have an mat-accordion with ngfor, when you click on the panel a table show up.
Everything work as expected beside Mat sort, its only sort the first table.
I read that i need to put template reference variable inside each table but how can i do it dynamically ? or there some other way to achieve that.
Here is my code :

  <mat-accordion style="width: 80%">
<mat-expansion-panel *ngFor="let customer of customers; let i = index" (opened)="openPanel(customer);">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{customer.name}}
    </mat-panel-title>
    <mat-panel-description>
      <span style="text-align:center">{{" Active Calls: " + customer.active}}</span>
      <span style="margin-left: 100px;">{{" Talking Calls: " + customer.talking}}</span>
    </mat-panel-description>
  </mat-expansion-panel-header>
  <table #HERE-I-NEED-TO-PUT-DYNMIC-ID mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
    <ng-container *ngFor="let column of tableColumns;" matColumnDef="{{column.field}}">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> {{column.name}} </th>
      <td mat-cell *matCellDef="let element">
         <span *ngIf="column.field !== 'answered'"> {{element[column.field]}} </span>
         <span *ngIf="column.field === 'answered' && element[column.field] > 0">{{getTime(element[column.field] * 1000) | date: 'HH:mm:ss'}}</span>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</mat-expansion-panel>

Thanks.

Answer

chifangjang picture chifangjang · Dec 26, 2018

I solved the problem by using square brackets.
The code as below.

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