我正在尝试按角7对一个表MatSort进行排序,并且对角进行了新的排序。数据在dataSource中,并正确显示。我的数据来自我为调用后端而创建的服务,然后设置this.dataSource.sort = this.sort,如下面的示例所示:
https://stackblitz.com/angular/qlbmkgjnvya?file=main.ts (来自角度文档!)
我试着跟随角度文档中的例子,但是我觉得我遗漏了一些东西,因为排序对我的示例没有任何作用,但是当我以它们为例并在本地使用它时,它工作得很好。
//构成部分
import {MatSort} from '@angular/material/sort';
...
dataSource: MatTableDataSource<any[]>;
@ViewChild(MatSort) sort: MatSort;
...
ngOnInit() {
this.api.getData().subscribe(data => {
this.data= data; // this is an array of the data
this.dataSource = new MatTableDataSource(this.data); // works enough to display on the page without errors
this.dataSource.sort = this.sort; // has to be in here to ensure no race condition between the api call and setting the sort property
});
//view (component.html)
<table mat-table #table [dataSource]="dataSource" matSort>
<!-- Title Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
<td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
没有显示错误消息,但表没有更新。
发布于 2019-06-24 02:17:01
如果数据名与列名不匹配,排序函数不知道对哪些数据进行排序,因此它最终什么也不做(?)而不是抛出错误。不知道为什么我不早点想到这个。
发布于 2020-02-12 13:02:29
在更改列以尊重显示列时,我遇到了同样的问题,并解决了这个问题,如下所示:
displayedColumns: string[] = ['dataID'];
<table mat-table #table [dataSource]="dataSource" matSort>
<!-- Title Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
<td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
https://stackoverflow.com/questions/56729006
复制相似问题