Angular

How to make reusable pipes in Angular

How to Make Reusable Pipes in Angular

If you are wondering about how to create reusable pipes for Angular components then you all are in the right place. Reusable pipes in angular can be created with help of custom pipes which can be used in many ways like sorting the array or an array of objects.

How to Make Reusable Sorting Pipes in Angular

In this tutorial we are are going to learn about the reusable sorting pipe in Angular and how it can be built in Angular. So keep reading.

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 the code given below, you need to pass two variable values i.e direction on which you need to sort the array and prop. The prop is an optional parameter. Other than this, if you need to sort an array of the object then you also need to pass the key of the objects.

Make sure your pure should be false in your pipe metadata configuration. When you use pure false configuration angular will keep the sorting order even if you add new items into the array.

So this is how you make a custom reusable sorting pipe in Array. Thanks for reading.

Leave a Comment