如何以编程方式对 MatTableDataSource 进行排序? [英] How to sort MatTableDataSource programmatically?

查看:31
本文介绍了如何以编程方式对 MatTableDataSource 进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式对 MatTableDataSource 进行排序,以便在查看特定移动布局中的数据时,可以通过使用按钮而不是通过表格列标题对数据进行排序.但是,我在这样做时遇到了麻烦.

I'm trying to sort the MatTableDataSource programmatically so that I can sort the data via the use of a button rather than by the table column header when viewing the data in a specific mobile layout. However, I'm having trouble doing so.

我已经遵循了这篇博文的建议,但没有反映数据排序.使用与表格相同的数据的移动版式设计:

I've followed this post's advice on how to do it but the data sort is not being reflected. The mobile layout design for using the same data as the table:

<mat-card matSort *ngFor="let item of dataSource.filteredData">

我用来尝试对数据进行排序的函数是:

The function I'm using to try and sort the data is:

sortDataSource(id: string, start: string){
  this.dataSource.sort.sort(<MatSortable>({id: id, start: start}));
}

通过点击 mat-menu 中的按钮调用,例如

which is called from tapping onto a button within a mat-menu e.g.

<mat-menu #sortMenu="matMenu" yPosition="below" [overlapTrigger]="false">
            <button mat-menu-item (click)="sortDataSource('createdDate', 'asc')"><span>Creation Date</span><mat-icon>arrow_upward</mat-icon></button>

对此的任何帮助将不胜感激!

Any help on this would be greatly appreciated!

StackBlitz 链接.

添加我将数据分配给来自 Observable 数组的表数据源的位置:

Adding where I'm assigning the data to the table's dataSource which comes from an Observable array:

this.data$.subscribe(data => {
      this.dataSource.data = data;
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
}

编辑 2:通过使用 *ngFor 将matSort"添加到 mat-card 以创建 的移动布局版​​本,删除了已修复的错误图像垫表.

Edit 2: Removed error image as fixed by add "matSort" to the the mat-card using *ngFor for creating the mobile layout version of the mat-table.

推荐答案

UPDATE

已在 Github.com 上向 Material 团队报告了一个错误.这似乎目前是不可能的.请使用手动方法或实现您自己的排序标题.

A bug was already reported to the Material team over at Github.com. It seems that this is currently not possible. Please use a manual approach or implement your own sorting header.

尝试手动对数据源的数据进行排序:

Try manually sorting the data of the datasource:

sortDataSource(id: string, start: string) {
    this.dataSource.sort.sort(<MatSortable>({ id: id, start: start }));
    this.dataSource.data.sort((a: any, b: any) => {
        if (a.createdDate < b.createdDate) {
            return -1;
        } else if (a.createdDate > b.createdDate) {
            return 1;
        } else {
            return 0;
        }
    });
}

您可以使用函数的 id 和 start 参数轻松地使其更通用.

You can easily make this more generic using the id and start parameters of your function.

这篇关于如何以编程方式对 MatTableDataSource 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆