Search code examples
angularangular-materialmat-table

mat-sort ascending with null values to last


I have a mat-sort-header with a date .I want to sort the table data with ascending based on dates , but want the null dates displayed last. The problem is that when im sorting by asccending , the null dates are shown first.

    <table  mat-table [dataSource]="dataSource" class="list-table list-table"
     matSort matSortActive="due_date" matSortDirection="asc" matSortDisableClear>   
     
     <ng-container matColumnDef="due_date">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>{{ "DUE DATE" | translate }}</th>
        <td mat-cell *matCellDef="let element">
          <span *ngIf="element?.due_date!==null">{{ element.due_date | dateTranslation }}</span>
          <span *ngIf="element?.due_date==null">{{'NO DUE DATE'|translate}}</span>
        </td>
      </ng-container>

What are the options to display null values to last when ordered by ascending?


Solution

  • My solution was, making a custom sort and hooking to ngAfterViewInit:

     ngAfterViewInit() {
      this.dataSource.sortData = (data, sort: MatSort) => {
      let sortedData = [];
      sortedData = data.sort((a, b) => {
        const direction = this.getSortingOrder(sort.direction, a, b);
        if (!direction[0][sort.active] || !direction[1][sort.active]) {
          return sort.direction === "asc" ? 0 : -1;
        } else {
          return direction[0][sort.active]
            .toString()
            .localeCompare(direction[1][sort.active]);
        }
      });
      return sortedData;
       };
     }
    
    
      getSortingOrder = (order, a, b) => {
        const sorted = order === "asc" ? [a, b] : [b, a];
        return sorted;
      }
    

    This will push the null values to last when sorted by ascending