0

I am working with Angular Material Table. I am trying to implement custom sorting behavior.

I am already using a sortingDataAccessor like this:

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

However, I have a problem with another column now. It is a column which contains strings with numbers and text.

The data in the table column looks like this:

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

but should look like this:

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

I would like to add a custom sorting behavior like it is explained in this post, but I do not understand how sort and sortingDataAccessor are working together. I actually do not understand the difference between them at all.

Can anyone explain the difference to me and how I could apply this sorting behavior?

Michael Andorfer
  • 1,660
  • 5
  • 25
  • 45

1 Answers1

2

You may generate and return comparable value in sortingDataAccessor. In your case it may be:

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

In my case, I using code below:

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