Angular使用javascript进行排序管道

时间:2018-01-31 15:04:03

标签: arrays angular typescript pipe

当我在Angular2中构建排序管道时,我有一个问题 这是我的管道代码:

enter image description here

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

@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {

  transform(value: any, propName: string): any {

    return value.sort((a,b)=> {
      return a[propName]-b[propName];
      // if(a[propName]>b[propName]) {
      //   return 1;
      // } else {
      //   return -1;
      // }
    });        
  }      
}

当我在评论中使用代码时,管道可以工作,但是当我使用返回[propName]-b[propName];时,它无效;

3 个答案:

答案 0 :(得分:1)

要使排序正常工作,必须返回一个整数(see reference)。您确定,减去您的属性将始终返回这些值吗?

答案 1 :(得分:0)

取决于您要分类的内容。如果值是一个数字,它应该工作。如果它是一个字符串,则返回一个NaN。第二种解决方案更好。

答案 2 :(得分:-1)

此代码选择管道传递的项目对象列表的属性,并考虑空值。

下面,您可以使用* ngFor查看管道的外观:

<tr *ngFor="let item of Clients | sort: sortType: sortDirection">

在下面您可以看到单击列标题时,箭头会更改箭头的方向,并使排序输出在排序管道内递增或递减。

<th>
        <div class="d-flex flex-row hoverOver">
          <span class="text-nowrap">Quantity</span>
          <i class="fa hoverTrans align-self-center mx-1" [ngClass]="{'fa-arrows-v': column != 'created',
            'fas fa-long-arrow-up': !sortDirection,
            'fas fa-long-arrow-down': sortDirection }" (click)="sortType = 'qty'; sortDirection = !sortDirection">
          </i>

下面是排序管道:

transform(items: any, sortType: any, sortDirection: any): any {

    const direction = sortDirection ? -1 : 1;

    items.sort((a, b) => {
      if (a[sortType] < b[sortType] || (a[sortType] === null && b[sortType] !== null) || (a[sortType] === "" && b[sortType] !== null)) {
        return -1 * direction;
      } else if (a[sortType] > b[sortType] || (a[sortType] !== null && b[sortType] === null) || (a[sortType] !== null && b[sortType] === "")) {
        return 1 * direction;
      } else {
        return 0;
      }
    });

    return items;
  }