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

查看:82
本文介绍了如何以编程方式对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菜单中的按钮来调用的.

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数组的表的dataSource的位置:

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;
}

通过使用 * ngFor mat-card 中添加"matSort"来创建的移动版式,已修复了错误图像.垫表.

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.

推荐答案

更新

已经通过 Github.com 向材料团队报告了一个错误.目前看来这是不可能的.请使用手动方法或实现您自己的排序标题.

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天全站免登陆