【问题标题】:Angular using javascript to make sort PipeAngular使用javascript进行排序管道
【发布时间】:2018-01-31 15:04:03
【问题描述】:

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

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;
      // }
    });        
  }      
}

当我在 cmets 中使用代码时,管道可以工作,但是当我使用 return a [propName]-b[propName]; 时它不工作;

【问题讨论】:

标签: arrays angular typescript pipe


【解决方案1】:

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

【讨论】:

  • 谢谢你的回复,我想试试这个,因为我看到了w3schools.com/js/tryit.asp?filename=tryjs_array_sort2
  • @Mia 我编辑了我的答案以反映我犯的错误。您可以减去数字,但您的答案也必须是数字。所以你必须确定,每个对象都有这个参数(你不能减去未定义的),并且返回值可以转换为数字(例如5 - null 将产生5,但5 - 'st' 将产生NaN)。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    您可以在下面看到带有 *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;
      }
    

    【讨论】:

    • 不要使用图片,而是将代码写成代码块。更具可读性
    • 感谢您的反馈,我已更新我的答案以提高可读性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-12-13
    • 2015-01-01
    相关资源
    最近更新 更多