Sorting Date field in Material Table (Mat Table) in angular 8.

Aman Sharma
0

In this article we’ll learn how to sort the Date column in the mat table. Normally sorting functionality considers each column as string and sort it accordingly. So an issue occurred with date columns. Sorting will not work for the date column.

 

In a previous article we have learnt how to sort nested columns in mat-table. Following code snippets explain Date as well as nested column sorting.

 

Component.ts File

 

 

loadUserDetails() {

    this.status = status;

    this.userService.getUserDetail()

      .subscribe(data => {

        this.dataSource.data = data;

        this.dataSource.paginator = this.paginator;

        this.dataSource.sort = this.sort;      

       

        this.dataSource.sortingDataAccessor = (item, property) =>

          switch (property) {

            case 'date':  return new Date(item.reportDate);

            case 'userName': return item.user.userName;        

            default: return item[property];

          }

        };

      });

  }

 

 

 

In switch statements, we convert column to date column to make sorting work properly.

Component.html File

 

<mat-table #table [dataSource]="dataSource" matSort class="table table-hover table-bordered mb-0 crew-table table-striped">

     

    <ng-container matColumnDef="date">

      <mat-header-cell *matHeaderCellDef mat-sort-header>Date</mat-header-cell>

      <mat-cell *matCellDef="let row"> {{row.date|date:'dd-MMM-yyy'}}</mat-cell>

    </ng-container>

 

    <ng-container matColumnDef="userName">

      <mat-header-cell *matHeaderCellDef mat-sort-header>User</mat-header-cell>

      <mat-cell *matCellDef="let row"> {{row.user?.userName}}</mat-cell>

    </ng-container>

 

    <ng-container matColumnDef="address">

      <mat-header-cell *matHeaderCellDef mat-sort-header>Address</mat-header-cell>

      <mat-cell *matCellDef="let row"> {{row.address}}</mat-cell>

    </ng-container>

 

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

  </mat-table>

 

 

 

Please go through the article and put a comment in the comment section, if you have any query. 

 

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !