角度4 - 多个字段的管道排序

时间:2018-04-01 03:56:18

标签: angular angular-pipe

在Angular 4中我有如下列表:

[{first: 'Peter', last: 'Smith'}
{first: 'John', last: 'Smith'},
{first: 'Tony', last: 'Hornet'},
{first: 'Sarah', last: 'Hornet'}]

我需要一个管道,它将按姓氏排序,然后排序。有谁知道如何最好地做到这一点?

2 个答案:

答案 0 :(得分:1)

您应该创建一个管道,该管道将名称作为参数并按特定顺序调用它。

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

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

  transform(array: any[], field: string): any[] {
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }

}

并在模板中

 <li *ngFor="let topic of names  | sortwithName: 'last' | sortwithName: 'first'">

<强> STACKBLITZ DEMO

答案 1 :(得分:1)

编辑:关注@ JBNizet的评论,由于性能原因,如果你有很多对象,创建一个管道实际上不是首选的方法。 (https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

因此,如果你有很多对象,你可以在ts代码中过滤它们,而不是在模板中。

array.sort((a: any, b: any) => {
  if (!a.last.localeCompare(b.last)) 
  {
    return a.first.localeCompare(b.first);
  }
  return a.last.localeCompare(b.last);
});

原始回答

创建管道确实是一个很好的解决方案

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

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

  transform(array: any[], field: string): any[] {
    array.sort((a: any, b: any) => {
      if (!a.last.localeCompare(b.last)) 
      {
        return a.first.localeCompare(b.first);
      }
      return a.last.localeCompare(b.last);
    });
    return array;
  }

}

https://stackblitz.com/edit/angular-filter-1svqdn?file=app/sortFilterPipe.ts

相关问题