OrderBy管道角4

时间:2018-01-02 11:51:10

标签: angular sorting typescript

我正在尝试根据此链接中的代码编写排序管道: http://www.advancesharp.com/blog/1211/angular-2-search-and-sort-with-ngfor-repeater-with-example 虽然我在处理未定义的值时遇到了麻烦。我的管道在没有任何未定义值的列上正常工作。但是当列管道中至少有一个未定义的值以奇怪的方式工作时。 我的代码如下:

html模板:

*ngFor="let candidate of filteredList | orderBy:{property: column, direction: direction}"

在html模板中选择列和方向,例如:

<th class="pointer" nowrap="nowrap" (click)="sort('lastName')">{{ 'candidates.candidates' | translate }}
      <i class="fa" [ngClass]="{'fa-sort': column != 'lastName',
                        'fa-sort-asc': (column == 'lastName' && !isDesc),
                        'fa-sort-desc': (column == 'lastName' && isDesc) }"
         aria-hidden="true"> </i></th>

阶by.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

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

  transform(candidates: Array<object>, args?: any): any {
    candidates = candidates || [];
    return candidates.sort(function (a, b) {

      if (a[args.property] === b[args.property]) {
        return 0;
      }
      if (a[args.property] === '' || a[args.property] === null || typeof a[args.property] === 'undefined') {
        return 1;
      }
      if (b[args.property] === '' || b[args.property] === null || typeof b[args.property] === 'undefined') {
        return -1;
      }
      if (a[args.property] < b[args.property]) {
        console.log(a[args.property] + ' wartosc property');
        return -1 * args.direction;
      } else if (a[args.property].toLowerCase() > b[args.property].toLowerCase()) {
        return 1 * args.direction;
      } else {
        return 0;
      }
    });
  }
}

component.ts:

public sort(property: string) {
    this.isDesc = !this.isDesc;
    this.column = property;
    this.direction = this.isDesc ? 1 : -1;
  }

我正在尝试许多不同的方法,但当时没有任何方法可以解决问题。

2 个答案:

答案 0 :(得分:0)

你能用lodash进行分类吗?

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

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

    transform(array: Array<{}>, args: string[]): Array<string> | Array<{}> {

        array = array || [];

        if (typeof args === 'undefined' || args.length !== 2) {
            return array;
        }

        const [key, direction] = args;

        if (direction !== 'ASC' && direction !== 'DESC') {
            return array;
        }

        return _.orderBy(array, (item:any) => item[key], direction.toLowerCase());
    }
}

答案 1 :(得分:0)

也许那是因为JavaSctipt Array.sort函数总是将undefined放在数组的末尾,并且未定义的值不会作为 a和b参数传递给 compareFunction

有关详情,请参阅此帖子:javascript array.sort with undefined values