angular - mat-sort-header/mat-sort 不适用于特定列

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/

相关文章:

.net - .NET 是框架还是库?

php - 如何在php中检查文件是否为视频类型?

ruby-on-rails - 手动安装 Xcode 命令行工具不起作用

python - 有效地比较python中的两组

regex - 正则表达式 ^(\d{1,2})$ 是什么意思?

performance - 给 Perl 的 print 一个列表或一个连接的字符串是否更快?

perl - 将哈希分配给哈希

php - 如何从页面(php)获取所有网址

memory - 使用 16 位整数的重要性

c# - 确认信息