1

I'm implementing the sortModule for angular material mat-table but for some reason it works perfectly for all the columns expect one. When I try to sort with it returns the table to it's initial situation but it does not sort.

html code for the mat-table:

<mat-table [dataSource]="demandesData" matSort matSortActive="dateCreation" matSortDirection="desc" >

columns that work:

 <ng-container matColumnDef="typeDemande" >
        <mat-header-cell *matHeaderCellDef mat-sort-header >
          Type demande 
        </mat-header-cell>
        <mat-cell *matCellDef="let element">
           {{ element.typeDemande }} 
        </mat-cell>

 </ng-container>
<ng-container matColumnDef="dateCreation">
        <mat-header-cell *matHeaderCellDef mat-sort-header> date création </mat-header-cell>
        <mat-cell *matCellDef="let element">
           {{ convertDate(element.dateCreation) }} 
        </mat-cell>
</ng-container>

the sorting is not working on this column:

<ng-container matColumnDef="nom">
        <mat-header-cell *matHeaderCellDef  mat-sort-header> Nom du collaborateur</mat-header-cell>
        <mat-cell *matCellDef="let element">
           {{ element.user_ajout.nom }} 
        </mat-cell>
</ng-container>

the data in the table: enter image description here

LA.
  • 143
  • 2
  • 14
  • I think it is working as intended, right now you are sorting based on data. When you will sort based upon the column specified by you, then in ascending order Uppercase values will come first and then lowercase and in descending vice versa. – Jasdeep Singh Apr 16 '20 at 18:58
  • in the image it's sorted by the third column, but when I try the second it does not work – LA. Apr 16 '20 at 19:27
  • please create stackblitz – Jasdeep Singh Apr 16 '20 at 19:29

1 Answers1

3

The columns that sort are simple properties that are direct children of the data row: dateCreation and typeDemand. They are also specified in their respective matColumnDef attribute. The middle column is a property inside the object user_ajout and not matching the matColumnDef attribute. Such "deep" values don't sort by the default comparator but need their custom sort comparator. This is called sortingDataAccessor.

Benny Halperin
  • 1,872
  • 3
  • 13
  • 18
  • 2
    Good example in the first answer here: https://stackoverflow.com/questions/48891174/angular-material-2-datatable-sorting-with-nested-objects – Benny Halperin Apr 16 '20 at 19:42