Angular mat-sort-header 5.2.4 的奇怪行为 [英] Strange behavior of Angular mat-sort-header 5.2.4
问题描述
我将 mat-table 与 angular material 的 mat-sort-header 结合使用.但奇怪的是,排序在 6 列(0 和 4)中的 2 列上工作正常.在对其他条目进行排序时,一个条目总是被拉到顶部,其余条目保持未排序或随机排序".我希望我能提供足够的代码来解决它.导入都在那里,这基本上是从
知道如何解决这个问题吗?
要使 matSortHeader 正常工作,您需要确保 matColumnDef 与数据源对象的属性名称匹配.例如:
<mat-header-cell *matHeaderCellDefmat-sort-header>我的标题文本</mat-header-cell><mat-cell *matCellDef="let row">{{row.status}}</mat-cell></ng-容器>
matColumnDef 是状态,所以你的行也应该有一个同名的属性:
导出类 MyDataSet {状态:字符串;}
否则排序操作符无法完成它的工作.您也可以编写自己的 dataAccessor:
this.datasource.sortingDataAccessor = ((item: MyDataSet, sortHeaderId: string) => {//编写代码以使用 sortHeaderId 从 item 中取出您的属性});
这里有一些进一步的信息:https://material.angular.io/components/table/api#MatTableDataSource
I am using the mat-table in combination with the mat-sort-header of angular material. But the strange thing is, the sorting works fine on 2 of 6 columns (0 and 4). When sorting the others, one entry is always pulled to the top and the rest stays unsorted or randomly 'ordered'. I hope I can provide enough code to get it solved. The imports are all there and this is basically copy-pasted from https://v5.material.angular.io/components/table/examples.
The table
every other column looks like the one in the snippet
<mat-table #matTable [dataSource]="dataSource" matSort>
<ng-container matColumnDef="Status">
<mat-header-cell *matHeaderCellDef mat-sort-header
....
TypeScript
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
ngOnInit() {
this.dataSource = new MatTableDataSource(this.projectlist);
}
//no specific code for sorting needed (I think)
I'm sorry for the screenshot being german, but you should see what I mean.
Sorted
Any idea how to fix this?
To get matSortHeader working you need to make sure that your matColumnDef matches the property name of your datasource object. For instance:
<ng-container matColumnDef="status">
<mat-header-cell *matHeaderCellDef
mat-sort-header>
My header text
</mat-header-cell>
<mat-cell *matCellDef="let row">
{{row.status}}
</mat-cell>
</ng-container>
matColumnDef is status so your row should also have a property with the exact same name:
export class MyDataSet {
status: string;
}
Otherwise the sort operator cannot do its job. You could also write your own dataAccessor:
this.datasource.sortingDataAccessor = ((item: MyDataSet, sortHeaderId: string) => {
// write code to get your property out of item using sortHeaderId
});
Some further information here: https://material.angular.io/components/table/api#MatTableDataSource
这篇关于Angular mat-sort-header 5.2.4 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!