Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mat table with ngFor and sorting

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.

like image 265
Avihay m Avatar asked Jul 15 '18 07:07

Avihay m


People also ask

What is matSort?

The matSort and mat-sort-header are used, respectively, to add sorting state and display to tabular data. Sorting overview.

What is matColumnDef?

Defines a set of cells available for a table column. Selector: [matColumnDef]

How do I disable mat sort?

We can disable the sorting of a table in 2 ways: We can add property matSortDisabled on matSort directive, or. Add disabled attribute on any single table header.


1 Answers

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>
like image 144
chifangjang Avatar answered Sep 18 '22 16:09

chifangjang