In client-side applications, we may need to filter out a set of data based on some unique values of the property passed to it. This type of data set can be a list of items with a parent-child relationship where they need to refine the child results based on parent id in it.
In Angular applications, we can do so by using Filter Pipes which can be easily used on a data object with custom login.
The Pipe Filter we are going to discuss will take a custom [key] name on which we want to filter child values. For example, there are following two data sets:
recipes = [ { "id":1, "name":"Burger" }, { "id":2, "name":"French Fries" }, { "id":3, "name":"Chowmein" } ] ingredients = [ { "id":1, "parentId":1, "name":"Potatoes" }, { "id":2, "parentId":1, "name":"Beans" }, { "id":3, "parentId":1, "name":"Buns" }, { "id":4, "parentId":1, "name":"Carrots" }, { "id":5, "parentId":2, "name":"Cooking Oil" }, { "id":6, "parentId":2, "name":"Potatoes" }, { "id":7, "parentId":2, "name":"Pepper" }, { "id":8, "parentId":2, "name":"Salt" }, { "id":9, "parentId":3, "name":"Hakka Noodles" }, { "id":10, "parentId":3, "name":"Green Vegies" }, { "id":11, "parentId":3, "name":"Tomato Sauce" }, { "id":12, "parentId":3, "name":"Soya Souce" } ]</pre> If we look at the objects above, in recipes there are two properties id and name. In the ingredients object, there is a parentId property that reflects the id of recipe. To show ingredients of a particular recipe selected, we will create a generic Angular filter pipe, where we will pass the property name on which we want to filter out ingredients which is the <code>parentId
here.Create a Filter Pipe
Using NG CLI tool, we can create a new Filter pipe using the generate command s shown below:$ ng generate pipe pipes/filterParent</pre> Above command will create a new pipe file <strong>pipes/filter-parent.pipe.ts</strong> with the following code in it: <pre class="wp-block-prismatic-blocks"><code class="language-javascript">import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filterParent' }) export class FilterParentPipe implements PipeTransform { transform(value: any, ...args: any[]): any { return null; } } </pre> <div> <div>Â For using a pipe in application components, we need to add it to its module's <code>declarations
array.
Leave a Reply