Angular Material 表利用名为 sortData()
的 MatTableDataSource 方法对表的数据源进行排序。 (https://material.angular.io/components/table/api#MatTableDataSource)。这是一个箭头函数:
sortData: ((data: T[], sort: MatSort) => T[])
我需要查看排序后的数据而不实际更改排序。例如,
this.dataSource.sortData = (sortData) => {
console.log(sortData);
return sortData;
};
这里的问题是我覆盖了 native 排序功能。 return sortData
返回原始数据,不进行任何排序。我想做的就是观察排序后的数据而不修改它。可以这样做吗?
最佳答案
您可以覆盖sortData
函数:
this.dataSource.sortData = this.sortData;
...
sortData = function(data: any, sort: MatSort) {
const active = sort.active;
const direction = sort.direction;
if (!active || direction == '') { return data; }
const sorted = data.sort((a, b) => {
let valueA = this.sortingDataAccessor(a, active);
let valueB = this.sortingDataAccessor(b, active);
// If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if
// one value exists while the other doesn't. In this case, existing value should come last.
// This avoids inconsistent results when comparing values to undefined/null.
// If neither value exists, return 0 (equal).
let comparatorResult = 0;
if (valueA != null && valueB != null) {
// Check if one value is greater than the other; if equal, comparatorResult should remain 0.
if (valueA > valueB) {
comparatorResult = 1;
} else if (valueA < valueB) {
comparatorResult = -1;
}
} else if (valueA != null) {
comparatorResult = 1;
} else if (valueB != null) {
comparatorResult = -1;
}
return comparatorResult * (direction == 'asc' ? 1 : -1);
});
console.log(sorted)
return sorted;
}
如您所见,我几乎没有更改 original function 。根据您的需要添加删除的类型。
附:覆盖 MatTableDataSource 中的一些函数 is a common practise :
May be overridden for a custom implementation of data ordering.
关于angular - 对 Angular Material 表进行排序时,您可以在不修改数据的情况下查看数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60157669/