Search code examples
angulartypescripthtml-tableangular-material

TypeScript/Angular - Sorting table works on all columns except the first


I have followed the official documentation and used the example provided but I cannot manage to get my first column sorted in descending order. When another column is used to sort and then the first column is clicked, it will only sort in ascending order. After that, there will be updates performed on the table no matter how many times the sort of the first column clicked.

I have added the project here: https://stackblitz.com/edit/angular-ivy-6xblrn. Please note that it doesn't look aesthetically pleasing but the up/down arrow will show if ran on a local machine (I had difficulty getting StackBlitz working).


Solution

  • You simply have to call the column the same as the field name of the object you have in the data array.

    The reason why the names have to match is that, if you notice, all this sorting is being done automatically by Angular material (think as a kind of "sintactic sugar").I mean, the sorting method is not programmed by us anywhere, it is done only by Angular Material.

    So the way mat-sort-header has to achieve this automatic sorting is by matching the name its columns (by the name of the one you want to sort) with the name of the field to be used as a reference when sorting.

    I leave you your own stackblitz working fine: https://stackblitz.com/edit/angular-ivy-njblvd?file=src/app/app.component.html

    P.S: I highlight you my changes:

    TS:

      displayedColumns: string[] = [
        'id',
        'firstName',
        'lastName',
        'age',
        'gender',
      ];
    

    HTML:

        <ng-container cdkFocusInitial matColumnDef="id">
          <th
            mat-header-cell
            *matHeaderCellDef
            mat-sort-header
            sortActionDescription="Sort by rank"
          >
            No.
          </th>
          <td mat-cell *matCellDef="let element">{{ element.id }}</td>
        </ng-container>