使用字母顺序与 Unicode 顺序不同的语言对 MatSort 进行排序?

Collation for MatSort with languages where alphabetical order is different from Unicode order?

在挪威语和丹麦语字母表中,Norwegian/Danish 个字符的正确顺序是:

  1. Æ
  2. Ø
  3. Å

但是,MatSort 对这些字符使用 Unicode 顺序:

  1. Å (197)
  2. Æ (198)
  3. Ø (216)

能否以某种方式实施整理来解决这个问题?

这是一个带有 table 的 stackblitz,可以按 "No." 和 "Name" 排序:

https://stackblitz.com/edit/angular-an1uqc-8mdqns

这是 table 中的数据:

 {position: 1, name: 'Alpha', description: 'Test123'},
  {position: 2, name: 'Bravo',  description: '0'},
  {position: 3, name: 'Charlie', description: 'aaa'},
  {position: 4, name: 'Delta',  description: ''},
  {position: 5, name: 'Echo',  description: '1'},
  {position: 6, name: 'Foxtrot',  description: '2'},
  {position: 7, name: 'ÆGamma',  description: ''},
  {position: 8, name: 'ØHotel',  description: '3'},
  {position: 9, name: 'ÅIndigo',  description: '1000'},

];

根据 Norwegian/Danish 字母表对最后三个项目(ÆGamma、ØHotel 和 ÅIndigo)进行排序的正确方法是:

  1. Æ伽玛
  2. Ø酒店
  3. Å靛蓝

但是 MatSort 对这些字符使用 Unicode 数字并像这样排序:

  1. Å靛蓝 (197)
  2. Æ伽玛 (198)
  3. Ø酒店 (216)

感谢阅读! :]

您需要使用 matSortChange to implement a custom sort, in this case a localized sort. This can be done using String.prototype.localCompare 和语言标识符 da-DK:

模板:

<table
  mat-table [dataSource]="sortedData"
  matSort (matSortChange)="sortData($event)"
  class="mat-elevation-z8">

组件:

sortData(sort: Sort) {
  const data = ELEMENT_DATA.slice();
  if (!sort.active || sort.direction === '') {
    this.sortedData = data;
    return;
  }

  this.sortedData = data.sort((a, b) => {
    const isAsc = sort.direction === 'asc';
    switch (sort.active) {
      case 'position': return compareNumber(a.position, b.position, isAsc);
      case 'name': return compareString(a.name, b.name, isAsc);
      case 'description': return compareString(a.description, b.description, isAsc);
      default: return 0;
    }
  });
}

// ...

function compareNumber(a: number, b: number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

function compareString(a: string, b: string, isAsc: boolean) {
  return a.localeCompare(b, 'da-DK') * (isAsc ? 1 : -1);
}

这是一个 example 的动作。

排序结果如下:

1 Alpha
// ...
6 Foxtrot
7 ÆGamma
8 ØHotel
9 ÅIndigo

然后反过来:

9 ÅIndigo
8 ØHotel
7 ÆGamma
6 Foxtrot
// ...
1 Alpha

希望对您有所帮助!