Skip to content Skip to sidebar Skip to footer

How To Create A Custom Sorting Pipe In Angular 4

how to create a custom sorting pipe in angular 4 component.ts @Component({ selector: 'app-cinemas', templateUrl: './cinemas.component.html', encapsulation: ViewEncapsu

Solution 1:

The orderBy pipe was removed from Angular 2 because generally filtering logic like this should be done within the component. Since you already return filteredCinema from your component, it would be best to apply custom sorting here.

Assuming you want to have a case-insensitive sorting by cinema_name, do something like this in your subscribe callback:

this.filteredCinema = return items.sort((a, b) => {
    letaLC: string = a.cinema_name.toLowerCase();
    letbLC: string = b.cinema_name.toLowerCase();
    return aLC < bLC ? -1 : (aLC > bLC ? 1 : 0);
});

(Also you should first ensure that response is not empty in this case, for simplicity I left that out)

If you wish filtering to be case-sensitive, simply remove the .toLowerCase calls.

If you still want to do it via a pipe, you should continue reading the tutorial first, because you are lacking the sorting mechanism.

Let's say you wanted a pipe orderByCinemaName:

@Pipe({
  name: 'orderByCinemaName'
})
exportclassOrderByCinemaNamePipeimplementsPipeTransform {  
  transform(items: any[]): any[] {
    return items.sort((a, b) => {
        letaLC: string = a.cinema_name.toLowerCase();
        letbLC: string = b.cinema_name.toLowerCase();
        return aLC < bLC ? -1 : (aLC > bLC ? 1 : 0);
    });
  }
}

UPDATE

Fixed the sorting algorithm.

Post a Comment for "How To Create A Custom Sorting Pipe In Angular 4"