如何对 Angular 7 Material 数据 table 中的日期进行排序?

How to sort dates in Angular 7 Material Data table?

我使用 ng generate @angular/material:table demoTable 创建了一个数据table。

我必须按日期列排序。在以前的 Angular 版本中,我可以使用 sortingDataAccessor 来达到这个目的,但由于某些原因,我不能在这里使用它。

有没有人尝试过使用 Angular 7(更具体地说是在使用 ng generate 命令创建 DataTable 之后)?

执行这些步骤,您应该能够对日期列进行排序:

HTML:

  1. 添加MatSortModule

    import {MatSortModule} from '@angular/material/sort';
    
    imports: [
      ...
      MatSortModule
      ...
    
  2. matSort 添加到您的表格

    <table matSort ...
    
  3. mat-sort-header 添加到您的列 th

    <th mat-sort-header="date"
    

有了这个,您的专栏将发出 matSortChange 事件

  1. 注册matSortChange事件

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

TS:

  1. 按照您的方式实现 sortData(),如下所示:

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

您可以在 Angular Material Docs

中查看更多详细信息

另外,为您创建了这个 DEMO 以防您弄乱它

您可以使用 MatSort 进行排序,如下所示:

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

在你的 html:

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

在你的 ts 组件中声明:

sortableList: MatSort;

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

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

这应该适用于所有列类型。