简体   繁体   中英

How to sort dates in Angular 7 Material Data table?

I created a datatable using ng generate @angular/material:table demoTable.

I have to sort by the date column. In the previous Angular versions I was able to use sortingDataAccessor for this purpose but for some reasons, I am not able to use that here.

Has anyone tried that using Angular 7 (more specifically after using the ng generate command to create the DataTable) ?

Take this steps and you should be able to sort your date column:

HTML :

  1. Add MatSortModule

     import {MatSortModule} from '@angular/material/sort'; imports: [ ... MatSortModule ... 
  2. Add matSort to your tabel

     <table matSort ... 
  3. Add mat-sort-header to your column th

     <th mat-sort-header="date" 

Having this your column will emit the matSortChange event

  1. Register matSortChange event

     <table matSort (matSortChange)="sortData($event)"> 

TS :

  1. Implement sortData() your way, something like this:

     sortData(event) { this.(your-list) = this.(your-list).sort((a, b) => { return a.date > b.date ? 1 : -1; } } 

You can see this in greater details in Angular Material Docs

Also, created this DEMO for you in case you get messed up with this

You can do the sort usling MatSort like following:

import { MatSort, MatTableDataSource } from '@angular/material';

in your html:

 <mat-table #matSort="matSort" matSort>

in your ts component declare:

sortableList: MatSort;

@ViewChild('matSort') set yourDataSource(ms: MatSort) {

    this.sortStudentDetails = ms;
    yourDataSoruce = new MatTableDataSource(yourList);
    yourDataSoruce.sort = this.sortableList;
  }

this should work for all columns types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM