首页 > 解决方案 > 在列值更改时禁用 Angular 表的自动排序

问题描述

当用户更改列中的值时,是否可以以某种方式禁用 Angular 表中的自动排序?Bcs 更改后立即对数据进行排序,当该列上存在活动排序时。如果我设置 dataSource.sort = null 排序被禁用,但数据排序返回到默认排序。我只想在列标题单击时对数据进行排序。

标签: angularsortingmat-tabledisable

解决方案


经过长时间的努力,我发现自己找到了解决方案。我用我的定义覆盖了默认排序方法:

    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;
  }

推荐阅读