繁体   English   中英

如何在Angular 7材料数据表中对日期进行排序?

[英]How to sort dates in Angular 7 Material Data table?

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

我必须按日期列排序。 在之前的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 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;
  }

这适用于所有列类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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