eba*_*nin 2 angular-material angular angular-material-table angular-material-7
Angular Material 表利用 MatTableDataSource 方法来sortData()对表的数据源进行排序。(https://material.angular.io/components/table/api#MatTableDataSource)。它是一个箭头函数:
sortData: ((data: T[], sort: MatSort) => T[])
Run Code Online (Sandbox Code Playgroud)
我需要查看排序后的数据而不实际更改排序。例如,
this.dataSource.sortData = (sortData) => {
console.log(sortData);
return sortData;
};
Run Code Online (Sandbox Code Playgroud)
这里的问题是我重写了本机排序功能。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;
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我几乎没有改变原来的功能。根据您的需要添加删除的类型。
ps 覆盖 MatTableDataSource 中的一些函数是一种常见的做法:
可以针对数据排序的自定义实现进行覆盖。
| 归档时间: |
|
| 查看次数: |
2766 次 |
| 最近记录: |