skip to Main Content

I am implementing a table with MatSort where every column sorting works except one (the third):

<ng-container matColumnDef="nbreEnregistrementTotal">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>N° enregistrement dans le fichier</th>
      <td mat-cell *matCellDef="let row"> {{row.nbreEnregistrementTotal}}</td>
    </ng-container>
    <ng-container matColumnDef="nbreMouvementsDetailsDiffusees">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>N° enregistrement acceptées</th>
      <td mat-cell *matCellDef="let row">{{row.nbreMouvementsDetailsDiffusees}}</td>
    </ng-container>
    <ng-container matColumnDef="nEnregistrementRejetes">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>N° enregistrement rejetées</th>
      <td mat-cell *matCellDef="let row">{{row.nbreEnregistrementTotal-row.nbreMouvementsDetailsDiffusees}}</td>
    </ng-container>

The column NEnregistrementRejetes is the difference between the previous two. I know I can calculate this on my API/typescript and return the difference result as a parameter for each row. But I am curious whether or not it would be possible to sort in this situation.

Thank you.

2

Answers


  1. The default sorting uses the column definition name

    Data accessor function that is used for accessing data properties for sorting through the default sortData function. This default function assumes that the sort header IDs (which defaults to the column name) matches the data’s properties (e.g. column Xyz represents data[‘Xyz’]). May be set to a custom function for different behavior.
    Source: https://material.angular.io/components/table/api#MatTableDataSource

    As you can see your first 2 examples satisfy this, while your third column is named nEnregistrementRejetes but accesses nbreEnregistrementTotal-row.nbreMouvementsDetailsDiffusees. You will have to write an own sortingDataAccessor to access this path

    this.dataSource.sortingDataAccessor = (entry, property) => {
      switch (property) {
        case 'nEnregistrementRejetes':
          return entry.nbreEnregistrementTotal-row.nbreMouvementsDetailsDiffusees;
        default:
          return entry[property];
      }
    }
    
    Login or Signup to reply.
  2. You only can sort by a property of your dataSource.data

    Also the another good answer, you can create as dataSource

    dataSource=new MatTableDataSource(this.yourData.map(x=>(
             {...x,
              nEnregistrementRejetes:x.nbreEnregistrementTotal-
                                     x.nbreMouvementsDetailsDiffusees
             })))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search