circuit

How to Apply a Filter to Angular for loop (*ngFor) in HTML

Filter Pipe which can filter the whole array of objects




Photo by Marc Babin on Unsplash

Photo by Marc Babin on Unsplash

We mostly do work with the larger data. There are always some requirements to filter the array of objects based on search criteria or filter the whole array of objects based on a given input.

Angular does provide some classic feature to make reusable code which can work throughout the application. Let's discuss on how to apply filter for *ngFor loop.

Let's understand what is a pipe in Angular?

The pipe was called a filter in Angular 1 and the name changed in later versions.

It has a “@Pipe” decorator and implements a transform method that works with all change detections.

import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
   name : 'test'
})
export class TestPipe implements PipeTransform {
   transform(args : any) : any{

   }
}

We can discuss more this in-depth later on.

Let's move to create a pipe that can filter an array of objects.

If we have an array of objects and we would like to filter based on the property name.

const data = [{
        name: 'atit',
        surname: 'patel'
    },
    {
        name: 'vinay',
        surname: 'panchal'
    },
    {
        name: 'ramesh',
        surname: 'shah'
    }
];

The template can look like this:

<input [(ngModel)] = searchTerm> Search

<li *ngFor="let value of data| testFilter:"name":"searchTerm" ">

Let's create pipe now.

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

[@Pipe](http://twitter.com/Pipe)({
    name: 'testFilter'
})

export class TestFilterPipe implements PipeTransform {
    transform(data: any[], filterType: Object): any {
        if (!data || !filter) {
            return data;
        }

return data.filter(item => item[filterType].indexOf(val) !== -1);
    }
}
}

You need to add it to the module.

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        TestFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

What if I want to search for all value with respect to all properties?

We can modify the filter like this:

data.filter(obj => {
    return Object.keys(obj).reduce((acc, curr) => {
        return acc || obj[curr].toLowerCase().includes(val);
    }, false);
});

You can also go with the npm library too.

ng2-search-filter

References:

How to apply filters to *ngFor?




Continue Learning