I have a question when I build sort pipe in Angular2
here is my pipe code:
![](https://www.manongdao.com/static/images/pcload.jpg)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(value: any, propName: string): any {
return value.sort((a,b)=> {
return a[propName]-b[propName];
// if(a[propName]>b[propName]) {
// return 1;
// } else {
// return -1;
// }
});
}
}
When I use the code in comments, the pipe works, but when I use return a [propName]-b[propName];
it is not working;
For sort to work, you must return an integer (see reference). Are you sure, that subtracting your properties will always return these values?
Depends on what you are sorting. If the value is a number it should work. If it's a string then a NaN is returned. Second solution is better.
This code selects the property of the list of items objects passed in by the pipe and takes into consideration null values.
Below you can see what the pipe will look like with the *ngFor:
<tr *ngFor="let item of Clients | sort: sortType: sortDirection">
Below you can see when the column header is clicked, the arrows change direction of the arrow and make the sort output ascending or descending within the sort pipe.
<th>
<div class="d-flex flex-row hoverOver">
<span class="text-nowrap">Quantity</span>
<i class="fa hoverTrans align-self-center mx-1" [ngClass]="{'fa-arrows-v': column != 'created',
'fas fa-long-arrow-up': !sortDirection,
'fas fa-long-arrow-down': sortDirection }" (click)="sortType = 'qty'; sortDirection = !sortDirection">
</i>
Below is the Sort Pipe:
transform(items: any, sortType: any, sortDirection: any): any {
const direction = sortDirection ? -1 : 1;
items.sort((a, b) => {
if (a[sortType] < b[sortType] || (a[sortType] === null && b[sortType] !== null) || (a[sortType] === "" && b[sortType] !== null)) {
return -1 * direction;
} else if (a[sortType] > b[sortType] || (a[sortType] !== null && b[sortType] === null) || (a[sortType] !== null && b[sortType] === "")) {
return 1 * direction;
} else {
return 0;
}
});
return items;
}