1) 需求:
在做数据列表展示时,默认排序很奇怪,需要重新定义。
2) 思路:
html:
<p-table (sortFunction)="customSort($event)" [customSort]="true" ></p-table>
3) 代码实现:
ts代码:
public customSort(event: SortEvent) {
event.data.sort((data1, data2) => {
const value1 = data1[event.field];
const value2 = data2[event.field];
let result = null;
if (value1 == null && value2 != null) {
result = -1;
} else if (value1 != null && value2 == null) {
result = 1;
} else if (value1 == null && value2 == null) {
result = 0;
} else if (typeof value1 === 'string' && typeof value2 === 'string') {
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
} else {
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
return (event.order * result);
});
this.formListDataSorted = event.data;
}
4) 总结:
1) 在primeNG官方例子中,使用的是如下代码:
else if (typeof value1 === 'string' && typeof value2 === 'string')
result = value1.localeCompare(value2);
localCompare()
可以再传一个参数指定语言。
2) 直接对string字符串进行大小比较,结果是从头开始比较每一位字符的charCode
的大小,直到比较出大小为止。