AngularJS PrimeNG 的 自定义排序customSort

本文介绍了在AngularJS中使用PrimeNG组件时遇到默认排序问题,如何通过自定义排序(customSort)来解决这一问题。详细阐述了需求背景、解决思路,并提供了HTML和TS代码实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AngularJS PrimeNG 的 自定义排序customSort

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的大小,直到比较出大小为止。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值