mat-sort
不适用于来自数据库的 mat-table
的一列,其余列工作正常。唯一的区别是,我正在从另一项服务中获取这一列的数据。
我试图用 ngAfterViewInit
解决它,但无济于事。
ngAfterViewInit(){
this.dataSource.sort = this.sort;
};
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Resource </th>
<td mat-cell *matCellDef="let element"> {{element.creator.name}} </td>
<td mat-footer-cell *matFooterCellDef> </td>
</ng-container>
displayedColumns: string[] = ['projectName', 'date', 'hours', 'description', 'name', 'location', 'Edit'];
@ViewChild(MatSort) sort: MatSort;
ngOnInit(){
this.dataSource.sort = this.sort;
}
最佳答案
不知道您的数据模型,像这样的事情应该可以解决您的问题(在您的 ngOnInit
中):
this.dataSource.sortingDataAccessor = (item, property) => {
if (property === 'name') {
return item.creator.name;
} else {
return item[property];
}
};
排序对这个字段不起作用,因为 Angular 试图通过字符串 ID 访问列数据,对于这个列来说是 name
,但列数据实际上位于 下element.creator.name
(Angular 在 element.name
下查找)。
有关更多信息,请查看完整文档 here (一直在页面底部)它指出:
Data accessor function that is used for accessing data properties for sorting through the default sortData function. This default function assumes that the sort header IDs (which defaults to the column name) matches the data's properties (e.g. column Xyz represents data['Xyz']). May be set to a custom function for different behavior.
https://stackoverflow.com/questions/56004835/