Unable to sort in reverse using PipeTransform in a

2019-08-26 07:51发布

I am unable to sort the data. I refered from this website -

http://www.advancesharp.com/blog/1211/angular-2-search-and-sort-with-ngfor-repeater-with-example

My data is not getting sorted in descending order -

Code -

transaction.component.ts file -->

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'orderBy' })

export class TransactionComponent implements OnInit,PipeTransform {

 isDesc: boolean = false;
 direction;
 column;

 sort(property){
 this.direction = this.isDesc ? 1 : -1;
 this.isDesc = !this.isDesc; //change the direction    
 this.column = property;

  };

 transform(records: Array<any>, args?: any): any {
   return records.sort(function(a, b){
    if(a[args.property] < b[args.property]){
      console.log("clicked on first")
        return -1 *args.direction;
    }
    else if( a[args.property] > b[args.property]){
      console.log("clicked on second")
        return 1 *args.direction;
    }
    else{
      console.log("clicked on third")
        return 0;
    }
  });
  };
  }

transaction.component.html -->

<tr *ngfor="let dat of result | filter:filterdata| orderBy : 
{property: 'LOG_ID',direction:direction } | paginate: { itemsPerPage: 
5, currentPage: p };let i = index ">

标签: html angular
1条回答
Melony?
2楼-- · 2019-08-26 08:18

Below is the code for sort-by pipe. Which handles all types of array string, number and array of objects. For array of objects you need to pass the key according to which you want to sort.

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

@Pipe({
  name: "sortBy"
})
export class SortByPipe implements PipeTransform {
  public transform(array: any[], reverse: boolean = false, prop?: string) {
    array=JSON.parse(JSON.stringify(array));
    if (!Array.isArray(array)) {
      return array;
    }
    if (array.length) {
      let sortedArray: any[];
      if (typeof array[0] === "string") {
        sortedArray = array.sort();
      }
      if (typeof array[0] === "number") {
        sortedArray = array.sort((a, b) => a - b);
      }
      if (typeof array[0] === "object" && prop) {
        sortedArray = array.sort((a, b) => a[prop].toString().localeCompare(b[prop].toString()));
      }
      if (reverse) {
        return sortedArray.reverse();
      } else {
        return sortedArray;
      }
    }
    return array;
  }
}

import it and add to declaration in your AppModule. And below is how to use.

<span>{{['asd', 'def', 'bghi', 'nhm'] | sortBy: reverse}}</span>
<br>
<span>{{[2, 8, 3, 6, 34, 12] | sortBy: reverse}}</span>
<br>
<span>{{[{name:'name2'} , {name:'name1'} , {name:'name3'}] | sortBy: reverse : 'name' | json}}</span>

Here is a demo on Stackblitz

With this you can pass a boolean value that decide the reverse order or not. Also you can toggle that Just click the button it will change the order.

Hope this helps :)

查看更多
登录 后发表回答