in Code, Tech Trends, Tutorials

Creating a Filter Pipe for Angular 2 (in Ionic 2)

Players organized by team in <ion-list>

Players organized by team in <ion-list>

I’ve been getting into the world of building cross-platform mobile apps using the Ionic 2 Framework with Angular 2 for Typescript. Yesterday I needed to build a view that displayed a list of players that were grouped by the team that they’re on. The final view is shown here on the right.

The solution was to create a custom pipe. Pipes are a way to transform data within templates specifically for the purpose of presentation.

Filtering a List of Objects

To start out, the layout displayed a list of Player objects. The raw list looks something like this:

The template code for displaying this list without filtering would look something like this:

However, we’d like to group these players by what team they’re on. The list of teams looks like this:

In order to get what we want, we have to create a custom pipe.

Creating a Custom Pipe

The pipe code looks like this:

The first parameter to this pipe is the list of objects to be filtered, e.g. players. The second parameter is an object specifying the filter conditions. Each key in the list of conditions should match a key from the target object type. To use this filter in your view you need to add the pipe to your Component as follows:

Note that this Component has two public properties (players and teams) that are populated in the constructor() so that the lists will be available to the view. The key lines here are line 5, where the filter pipe is imported, and line 9, where we tell the Component that we plan to use this pipe. Once we’ve done this, we can use the pipe in our view like this:

If you wanted to filter for more than one property value, you could change the value passed to the filter to be something like: {teamId:, firstName: 'Morgan'}, which would return only members of teams with the first name Morgan (I know this is silly, but I hope you see the point).


As you can see, the values that are filtered for can be dynamic, e.g. a team ID that changes as teams are looped through. An improvement might be to update the pipe to allow other types of search expressions, e.g. return players with first names that start with “M”. At any rate, I was very pleased by how clean and elegant this ended up being. Happy filtering!


Write a Comment


  1. Looks great but would be good to see all of your code such as the constructor setting up the two arrays. Do you have full sample source code available somewhere for further exploration – thanks!

    • I don’t see why not. Just use the value from the first select as the input to the filter and trigger it when the select changes.