How to sort MatTableDataSource programmatically?

Sna*_*ips 5 sorting angular-material angular mat-table

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">
Run Code Online (Sandbox Code Playgroud)

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}));
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Any help on this would be greatly appreciated!

Link to StackBlitz.

Edit: 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;
}
Run Code Online (Sandbox Code Playgroud)

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.

Jul*_*bos 5

更新

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


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

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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

  • 不过,我真的不想手动对数据进行排序。我想要一种访问 MatTableDataSource 内置排序方法的方法,因为我已经定义了如何在 `this.dataSource.sortingDataAccessor` 方法中对数据进行排序,以便我可以通过使用来模拟按下列标题的方式通过传递 `id` 和 `start` 属性来创建一个按钮。也许只是不可能这样做? (3认同)
  • 或者使用 asc 或 desc 更短: this.dataSource.data.sort( (a, b) =&gt; { return start === 'asc' ? a[id] - b[id] : (start === 'desc ' ? b[id] - a[id] : a[id] - b[id]); // 最后一个是默认值 } ); (2认同)