MatSort 的排序规则与字母顺序与 Unicode 顺序不同的语言?



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

  1. Æ
  2. Ø
  3. Å

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

  1. Å (197(
  2. Æ (198(
  3. 直径 (216(

是否可以以某种方式实现排序规则来解决此问题?

这是一个堆栈闪电战,其中包含一个可以按"否"和"名称"排序的表格:

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

下表中的数据如下:

{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'},
];

根据挪威语/丹麦语字母对最后三个项目(ÆGamma,ØHotel和ÅIndigo(进行排序的正确方法是:

  1. 埃加玛
  2. Ø霍特尔
  3. ÅIndigo

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

  1. 阿因迪戈 (197(
  2. 艾加玛 (198(
  3. Ø 霍特尔 (216(

感谢您的阅读! :]

您需要使用 matSortChange 来实现自定义排序,在本例中为本地化排序。这可以使用 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);
}

下面是一个实际示例。

排序结果如下:

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

然后反过来:

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

希望对您有所帮助!

最新更新