Category
Software Engineering
Published
May 12, 2016
Read
3 min
Sections
Article Purpose
Why IndexOfPipe?
Simple Example
Extended Example
Code
Author
Derek Knox
The purpose of this article is to provide an Angular 2 Pipe that allows any object collection to be declaratively filtered on any number of specific property names by a dynamic value.
There are a few discreet characteristics that make IndexOfPipe
valuable:
IndexOfPipe
. Since the above description is abstract, let's look at an actual scenario. The simplest scenario of where IndexOfPipe
is useful would be when a single text input field's value needs to filter a list (of image models in this case) where each model instance has many properties. Let's say each has a name
, tags
, and location
property. With IndexOfPipe
you can declaratively have the single dynamic input value match against any single or combination of the three property values. This results in an automatically filtered list.
Let us first look at the simpler declarative example:
Let's focus on just the contents of the structural *ngFor
directive:
We are declaring we want an <img>
for each image model found in the imageSettings.images
array. However, we want to filter the array based on two conditions:
imgModel
) must have a name
property (arg 1)imgModel.name.indexOf(imageSettings.filterQuery)
operation must pass (arg 2)The list will be filtered according to the imageSettings.filterQuery
value's presence within the value of the name
property.
As mentioned IndexOfPipe
can handle any property name(s). So let's add plurality. We do so simply by passing another string value to the array of property names. Nice and simple:
Now the list will be filtered when the imageSettings.filterQuery
input string value exists in any of the name
, tags
, or location
property values. Kinda cool.
A possible next logical step would be to make the imageSettings.filterQuery
argument an array as well. This could be useful, but I'm going to draw the line here. Feel free to take it to the next level if what you're creating would benefit.
Once Angular 2 officially launches, I'll make a simple codepen to provide the interactive example discussed in this article. In the mean time, you can get it on Github and run it locally. Hit me up on Twitter @derekknox if you have any thoughts or improvement ideas.
IndexOfPipe on Github