Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular generic pipe

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.

like image 839
Sampath Avatar asked Dec 08 '22 16:12

Sampath


1 Answers

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 🤓

like image 179
Daniel Kucal Avatar answered Dec 10 '22 12:12

Daniel Kucal