角2 |如何使用管道对数值进行排序?

时间:2017-11-13 05:53:46

标签: angular typescript angular-pipe

美好的一天,

如何使用管道对角度2中的数值进行排序?或者是他们用于排序数字的内置管道?

<div class="group group1">
<div *ngFor="let apidata of data">
  <div *ngIf="apidata.AssignmentNumber[0] == 1" class="box">
      <div class="box-assignmentnumber-holder">
        <span id="AssignmentNumber" [ngStyle]="{'color': apidata.AssignmentNumber[1] == 1 ? '#FF8C00' : 'green'}">{{apidata.AssignmentNumber | desc}}</span>
      </div>
      <div id="arrow" (click)="this.clickMe =! this.clickMe"></div>
  </div>
</div>

上面是我显示数字的代码,但我想按升序对它们进行排序。

2 个答案:

答案 0 :(得分:0)

Angular does not ship a sort pipe because they seem to think it degrades performance to an unacceptable degree. However, I have employed them and found them to be useful. You just need to write one.

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

@Pipe({name: 'sortBy'}) export class SortBy {
  transform<T>(
    values: T[] | undefined, 
    by: keyof T | ((x: T) => any), 
    direction?: 'ascending' | 'descending'
  ) {
   const thrust = direction || 'ascending';

   const getKey = typeof by === 'function' ? by : ((x: T) => x[by]);

   return values && values.slice().sort((x, y) => {
     const xKey = String(getKey(x));
     const yKey = String(getKey(y));
     return thrust === 'ascending'
       ? xKey.localeCompare(yKey)
       : yKey.localeCompare(xKey);
     });
  } 
} 

Now you have a generic sorting pipe that can take the property name is a string or a function that returns a property value, and optionally a direction.

答案 1 :(得分:-1)

you can refer this example of sorting numbers and words. this is inspired from http://embed.plnkr.co/DHLVc0

Example use

Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"

Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"

Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status', '-title']"

orderBy.ts

        import {Pipe, PipeTransform} from 'angular2/core';

        @Pipe({name: 'orderBy', pure: false})
        export class OrderBy implements PipeTransform {

            static _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
            }

            transform(input:any, [config = '+']): any{

                if(!Array.isArray(input)) return input;

                if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
                    var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
                    var desc = propertyToCheck.substr(0, 1) == '-';

                    //Basic array
                    if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
                        return !desc ? input.sort() : input.sort().reverse();
                    }
                    else {
                        var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                            ? propertyToCheck.substr(1)
                            : propertyToCheck;

                        return input.sort(function(a:any,b:any){
                            return !desc 
                                ? OrderBy._orderByComparator(a[property], b[property]) 
                                : -OrderBy._orderByComparator(a[property], b[property]);
                        });
                    }
                }
                else {
                    //Loop over property of the array in order and sort
                    return input.sort(function(a:any,b:any){
                        for(var i:number = 0; i < config.length; i++){
                            var desc = config[i].substr(0, 1) == '-';
                            var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                                ? config[i].substr(1)
                                : config[i];

                            var comparison = !desc 
                                ? OrderBy._orderByComparator(a[property], b[property]) 
                                : -OrderBy._orderByComparator(a[property], b[property]);

                            //Don't return 0 yet in case of needing to sort by next property
                            if(comparison != 0) return comparison;
                        }

                        return 0; //equal each other
                    });
                }
            }
        }