angular - 在列值更改时禁用 Angular 表的自动排序
问题描述
当用户更改列中的值时,是否可以以某种方式禁用 Angular 表中的自动排序?Bcs 更改后立即对数据进行排序,当该列上存在活动排序时。如果我设置 dataSource.sort = null 排序被禁用,但数据排序返回到默认排序。我只想在列标题单击时对数据进行排序。
解决方案
经过长时间的努力,我发现自己找到了解决方案。我用我的定义覆盖了默认排序方法:
this.dataSource.sortData = (
dataArray: ServicePartnerCategory[],
sortObj: MatSort
) => this.sortTableData(dataArray, sortObj);
在 sortTableData 我放了一个 if isSortingEnabled 并且我要么返回排序数组,要么返回前一个排序数组。这解决了问题,即 dataSource.sortData 每次数据发生变化时都会执行(参见文档)。我还需要省略大写字母并在最后放置空值,无论排序如何。
sortTableData(
dataArray: ServicePartnerCategory[],
sortObj: MatSort
): ServicePartnerCategory[] {
if (this.isSortingEnabled) {
switch (sortObj.direction) {
case 'asc':
dataArray.sort((a, b) => this.getSortIndex(a, b, sortObj, 'asc'));
break;
case 'desc':
dataArray.sort((a, b) => this.getSortIndex(a, b, sortObj, 'desc'));
break;
default:
dataArray.sort(
(a, b) =>
this.dataSource.data.indexOf(a[sortObj.active]) -
this.dataSource.data.indexOf(b[sortObj.active])
);
break;
}
this.lastSortArray = cloneDeep(dataArray);
}
return this.lastSortArray;
}
然后在更改功能中,我将 isSortingEnabled 设置为 false。此更改函数在 form.valueChanges 上调用
onChange: any = () => {
this.isSortingEnabled = false;
}
单击排序标题后,执行此功能:
onSortData($event) {
this.isSortingEnabled = true;
}
只是其余的功能:
/**
* Returns index wether the a should be sorted before or after b.
* Capitals are omited
* Empty value is always sorted to end of the list
* @param a first object for compare
* @param b second object to compare
* @param sortObj name of the object property to sort by
* @param sortDirection asc or desc
*/
getSortIndex(
a: ServicePartnerCategory,
b: ServicePartnerCategory,
sortObj: MatSort,
sortDirection: string
): number {
if (a[sortObj.active] === '' || a[sortObj.active] === null) return 1; //always move
//empty value to the end of the list
if (sortDirection === 'asc')
return this.getProperty(a, sortObj.active) >
this.getProperty(b, sortObj.active)
? 1
: -1;
return this.getProperty(a, sortObj.active) <
this.getProperty(b, sortObj.active)
? 1
: -1;
}
推荐阅读
- css - 属于嵌套在另一个元素的类中的多个类的 div 元素的 CSS 样式规则
- reactjs - 如何从 Cloud Firestore 获取数据
- python - 无法绘制 Zipf 的分布图
- c# - Entity Framework Migrations 给出以下错误:context has changed since the database is created
- swift - 仅在新添加的单元格处重新加载 TableView
- sql - postgresql 管理 15 亿行的表是否可以管理?
- visual-studio - 如何在我的 Web.config 中转换此元素?
- arrays - Google Sheet 中的 ARRAYFORMULA 是否区分硬编码范围和连接范围
- node.js - 如何提供每天(从午夜到午夜)和每 24 小时可兑换的优惠?
- javascript - html中的电子邮件表格,但将第一列格式化为日期