【问题标题】:Angular pipe sorting角管分拣
【发布时间】:2018-06-21 13:02:41
【问题描述】:

根据这个问题-> Ascending and Descending Sort in Angular 4

我做了同样的管道,但它不能自然地对数字进行排序。我的意思是 2 > 然后 11。

如何修改此管道以对字符串和数字进行排序?

@Pipe({
    name: 'orderBy'
})

export class OrderByPipe implements PipeTransform {

    transform(records: Array<any>, args?: any): any {
        if (records && records.length > 0) {
            return records.sort(function (a, b) {                 
                if (a[args.property] < b[args.property]) {
                    return -1 * args.direction;
                } else if (a[args.property] > b[args.property]) {
                    return 1 * args.direction;
                } else {
                    return 0;
                }
            });

        }
    }
}

【问题讨论】:

  • 你能举个例子,你的输入和参数是什么样的,你期望的输出是什么?
  • 嗨,实际上它与来自链接的完全相同。输入是来自 html 表格列的值。

标签: angular sorting pipe


【解决方案1】:

那是因为您将值排序为字符串 - 按字典顺序排列。管道的输入似乎是Array&lt;{ [propertyName: string]: [value: string] }&gt; 类型。

在比较之前确保输入属性值是数字或将值转换为number

如果您需要根据传入管道的数据类型进行排序,您可以使用以下内容:

@Pipe({
  name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {
    if (records && records.length > 0) {
      return records.sort(
        (a, b) => args.direction * (
          typeof a[args.property] === 'number'
            ? (a[args.property] - b[args.property])
            : a[args.property] > b[args.property] ? 1 : -1)
      );
    }
  }
}

希望这会有所帮助:-)

【讨论】:

    【解决方案2】:

    这是我在 Angular 中使用管道订购的解决方案。

    +额外功能:使用第三个参数升序和降序。

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'orderBy'
    })
    export class OrderByPipe implements PipeTransform {
    
      transform(value: any[], key: string, dir: number = 1): any {
        if (!value || !key) {
          return value;
        }
    
        value.sort( (a, b) => {
          return ('' + a[key]).localeCompare( ('' + b[key]) ) * dir;
        });
    
        return value;
      }
    
    }

    我总是将值转换为字符串,因为比较最容易。

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2016-01-13
      • 2018-04-21
      相关资源
      最近更新 更多