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 ">
Below is the code for sort-by pipe. Which handles all types of array
string
,number
andarray of objects
. For array of objects you need to pass the key according to which you want to sort.import it and add to declaration in your AppModule. And below is how to use.
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 :)