角度5,orderBy asc / desc

时间:2018-03-25 13:47:09

标签: angular5 angularjs-orderby

是否可以选择在orderBy管道中通过asc / desc更改排序?

数组:

this.testArr = [{name: 'bbb', id: '1'}, {name: 'ccc', id: '2'}, {name: 'aaa', id: '0'}];

在HTML中:

<ul><li *ngFor="let item of testArr | orderBy: 'id' : true"><div>{{item.id}}</div></li></ul>

将'true'替换为'false'/'asc'/'desc'不起作用。 所需的输出应为:0,1,2和另一个参数:2,1,0。

谢谢。

2 个答案:

答案 0 :(得分:6)

角度指南建议不要使用管道,因为性能和缩小问题 - the documentation

首选方法是在组件中使用过滤器/排序方法

<li *ngFor="let a of sortAccounts('id')">

然后在组件视图中

<li *ngFor="let a of sortAccounts('-id')">

function foo() {
  var a = 2;

  function baz() {
    console.log( a ); //2
  }

  bar(baz);
}

function bar(fn) {
  fn(); //look ma, I just saw a closure
}

答案 1 :(得分:1)

试试这段代码:          您可以创建自定义管道进行排序:

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

@Pipe({
    name: 'orderBy'
})
export class OrderBy{

 transform(array, orderBy, asc = true){

     if (!orderBy || orderBy.trim() == ""){
       return array;
     } 

     //ascending
     if (asc){
       return Array.from(array).sort((item1: any, item2: any) => { 
         return this.orderByComparator(item1[orderBy], item2[orderBy]);
       });
     }
     else{
       //not asc
       return Array.from(array).sort((item1: any, item2: any) => { 
         return this.orderByComparator(item2[orderBy], item1[orderBy]);
       });
     }

 }

 orderByComparator(a:any, b:any):number{

     if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
       //Isn't a number so lowercase the string to properly compare
       if(a.toLowerCase() < b.toLowerCase()) return -1;
       if(a.toLowerCase() > b.toLowerCase()) return 1;
     }
     else{
       //Parse strings as numbers to compare properly
       if(parseFloat(a) < parseFloat(b)) return -1;
       if(parseFloat(a) > parseFloat(b)) return 1;
      }

     return 0; //equal each other
 }
}

<强> .component.ts

list = [
    {
        name:"Terry",
        age:23
    },
    {
        name:"Bob",
        age:25
    }
    {
        name:"Larry",
        age:27
    }
];

order = "age";
ascending = true;

<强> html的

<div *ngFor="let person of list | orderBy:order:ascending">
    Name: {{person.name}}, Age: {{person.age}}
</div>