In this blog, you will learn how to make reusable sorting pipes for Angular components. With the use of Angular pipes you make custom pipes and sort the array and array of objects.
- import { Pipe, PipeTransform } from '@angular/core';
-
- @Pipe({
- name: 'tableSort',
- pure:false,
- })
- export class TableSortPipe implements PipeTransform {
-
- transform(value: any[], direcion: string, prop?: string): any {
- if (!value) {
- return [];
- }
- if (!direcion || !prop) {
- return value
- }
- if (value.length > 0) {
- const _direction = direcion === 'asc' ? -1 : 1,
- _isArr = Array.isArray(value),
- _type = typeof value[0],
- _flag = _isArr && _type === 'object' ? true : _isArr && _type !== 'object' ? false : true;
- value.sort((a, b) => {
- a = _flag ? a[prop] : a;
- b = _flag ? b[prop] : b;
- if (typeof a === 'string') {
- return a > b ? -1 * _direction : 1 * _direction;
- } else if (typeof a === 'number') {
- return a - b > 0 ? -1 * _direction : 1 * _direction;
- }
- });
- }
- return value;
- }
-
- }
In this above implementation, you have to pass direction and prop as parameters, you can see prop as an optional parameter. You have to pass the key of object when you want to sort the array of objects. Make sure your pure should be false in your pipe meta data configuration.
With you use pure false configuration angular will keep the sorting order even if you add new items into the array.
So you can use this pipe to sort array and array of objects.
Let me know if you're facing any issue related to this.
Cheers!!.