Create an Angular Pipe to Reverse Lists

Recently I was building a small application using Angular that displayed a list of IM Messages returned from a REST API. The array that came back was in the opposite than what we desired. The solution was to build a simple Pipe that reverses the Array.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {

  transform(value) {
    if (!value) return;

    return value.reverse();
  }
}

Let's walk through the code to see what we are doing. First we import Pipe and PipeTransform from @angular/core. Then we use the @Pipe decorator and pass in the name 'reverse' which we will use to call the Pipe. Next we export our class which implements PipeTransform so we can use the transform() method to return our new list. A simple check to see if there is a value being passed in and that it's not null then we can do our transformations and return the new Array. Finally don't forget to import your pipe into your NgModule so that the system will recognize it in your templates or components.

Now we can apply the Pipe to our *ngFor to reverse the order of the list.

<li *ngFor="let item of items | reverse">
  {{ item.name }}
</li>

Angular Pipes are very powerful display transformations that can be declared on HTML. Pipes take an input (data) and transform it as needed, then return the transformed data as the output. The example here transforms an array of data for an *ngFor, but you can use pipes on numerous template items. See the documentation below for more learning.

References:

Add new comment