Angular Material - mat-table sort row

1k views Asked by At

How to sort angular material mat table based on a row?, I know we can sort based on columns using mat-sort but the requirement is to sort based on the row when you double click on it.

enter image description here

<ng-container matColumnDef="Measure">
  <th mat-header-cell *matHeaderCellDef>Measure</th>
  <td mat-sort-header class="bold" mat-cell *matCellDef="let element">
      {{ element.name }}
  </td>
</ng-container>

Added the mat-sort-header directive to the td instead of th, but getting error - Cannot have two MatSortables with the same id (Measure).

3

There are 3 answers

0
Eliran Eliassy On

You can use the Material CDK-Table and set any kind of sorting you want. Check out the example from the official docs:

<table matSort (matSortChange)="sortData($event)">
   ....
</table>



sortData(sort: Sort) {
const data = this.desserts.slice();
if (!sort.active || sort.direction === '') {
  this.sortedData = data;
  return;
}

this.sortedData = data.sort((a, b) => {
  const isAsc = sort.direction === 'asc';
  switch (sort.active) {
    case 'name': return compare(a.name, b.name, isAsc);
    case 'calories': return compare(a.calories, b.calories, isAsc);
    case 'fat': return compare(a.fat, b.fat, isAsc);
    case 'carbs': return compare(a.carbs, b.carbs, isAsc);
    case 'protein': return compare(a.protein, b.protein, isAsc);
    default: return 0;
  }
});

}

0
Jacob-Jan Mosselman On

Add mat-sort-header to <th> instead of to <td>

I had this problem too today, it's just a silly mistake.

0
Muhammad Rehan Qadri On

I had:

displayedColumns: string[] = [
'guest-name',
'rental-name',
'check-in',
'check-out',
'check-in',
'guests',
'total',
'arrival-time',

]

Note check-in is being repeated twice which was causing following error:

"Cannot have two MatSortables with the same id"