无法在angular4中使用PipeTransform进行反向排序 [英] Unable to sort in reverse using PipeTransform in angular4
问题描述
我无法对数据进行排序.我是从这个网站引荐的-
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 -
代码-
transaction.component.ts 文件->
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 ">
推荐答案
下面是排序管道的代码.它处理所有类型的数组 string
, number
和对象数组
.对于对象数组,您需要根据要排序的键传递密钥.
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;
}
}
导入它并添加到AppModule中的声明中.下面是使用方法.
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>
通过此操作,您可以传递一个布尔值,该布尔值决定是否颠倒顺序.您也可以切换它,只需单击按钮即可更改顺序.
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.
希望这会有所帮助:)
这篇关于无法在angular4中使用PipeTransform进行反向排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!