【问题标题】:How do Angular Material MatSort and sortingDataAccessor work together?Angular Material MatSort 和sortingDataAccessor 如何协同工作?
【发布时间】:2019-08-21 12:21:07
【问题描述】:

我正在使用 Angular 材料表。我正在尝试实现自定义排序行为。

我已经在使用这样的 sortDataAccessor:

export class BillsComponent implements OnInit, OnDestroy {
  @ViewChild(MatSort, { static: true }) matSort: MatSort;
  data;

  displayedColumns = [
    'alreadyExported',
    'date',
    'invoiceNumber'
  ];

  ngOnInit() {
    this.loadData();
  }

  loadData() {
      ...
      .subscribe(data => {
        // Set new accessor
        this.data = new MatTableDataSource(data);
        this.data.sortingDataAccessor = (item, header) => {
          switch (header) {
            case 'date': return new Date(item.rechnungsdatum);
            case 'alreadyExported': return (item.export.exportFuerSteuerberater === null ? true : false);
            default: return item[header];
          }
        };
        this.data.sort = this.matSort;
      });
  }

  sortEvent() {
    this.data.sortingDataAccessor = (data, header) => data[header];
    this.data.sort = this.matSort;
  }
}

但是,我现在遇到了另一列的问题。它是一个包含带有数字和文本的字符串的列。

表格列中的数据如下所示:

  • BE-131
  • BE-130
  • BE-13
  • BE-129
  • BE-128
  • BE-110
  • BE-11
  • BE-109
  • BE-1

但应该是这样的:

  • BE-131
  • BE-130
  • BE-129
  • BE-128
  • BE-110
  • BE-109
  • BE-13
  • BE-11
  • BE-1

我想添加一个自定义排序行为,就像 post 中解释的那样,但我不明白 sort 和 sortDataAccessor 是如何协同工作的。我其实完全不明白它们之间的区别。

谁能向我解释其中的区别以及如何应用这种排序行为?

【问题讨论】:

  • 尝试创建代码的 Stackblitz。

标签: angular sorting angular-material


【解决方案1】:

您可以在sortingDataAccessor 中生成并返回可比较的值。在您的情况下,它可能是:

  • BE-00001
  • BE-00011
  • BE-00131

就我而言,我使用以下代码:

    private sortingDataAccessor = (item, property) => {
        switch (property) {
            case 'address': return this.getComparableAddress(item.address);
            default: return item[property] || '';
        }
    }

    private getComparableAddress(sourceAddress: string): string {
        let address = '';
        const blockLength = 3;

        const splittedAddress = sourceAddress.split(' ');
        for (const item of splittedAddress) {
            for (let i = 0; i < blockLength - item.length; i++) {
                address = address + '0';
            }
            address = address + item;
        }

        return address;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2018-01-16
    • 2019-10-07
    • 2021-06-13
    • 2020-10-17
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多