I would like to write generic pipe
. This is the pipe
where I have written for data type Category
order-by-category.ts
import { Pipe, PipeTransform } from '@angular/core';
import { Category } from '../../models/Category';
import { sortBy } from 'lodash';
@Pipe({
name: 'orderByCategory',
})
export class OrderByCategoryPipe implements PipeTransform {
transform(value: Category[]): Category[] {
return sortBy(value, (o: Category) => { return o.name; });
}
}
.html
<ion-item *ngFor="let c of categorySortedList | orderByCategory">
<ion-label>{{c.name }}</ion-label>
<ion-radio [value]="c.id" (ionSelect)="selectedCategory(c)"></ion-radio>
</ion-item>
Now I need to write the same kind of pipe
. But the data type
is different.
Now it is like this:
transform(value: BudgetGroup[]): BudgetGroup[] {
return sortBy(value, (o: BudgetGroup) => { return o.name; });
}
So I would like to use generic solution here rather than the same kind of 2 pipes
and also I need to maintain Typed pipe
too.
I'm just writing the same and found your question. The answer is quite obvious - generic function will work:
@Pipe({
name: 'orderByName',
})
export class OrderByNamePipe implements PipeTransform {
transform<T extends {name: string}>(value: T[]): T[] {
return value.sort((a, b) => {
if (a.name > b.name) return -1;
if (a.name < b.name) return 1;
return 0;
});
}
}
The original type is kept and seen in templates 🤓
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With