Ved Test
Ved Test

Reputation: 75

How to apply search filter on list in angular2?

I want to implement search filter on data list which is stored in array and I want to apply search filter same like search in data table. as shown in below image. but in that fields(name,address..etc) are not fixed.

based on search textbox value apply filter on below data

How can I achive this?

Upvotes: 3

Views: 8637

Answers (1)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37393

DEMO

if you want to filter by other fields just add them in the pipe:

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

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(items: any[], criteria: any): any {

        return items.filter(item =>{
           for (let key in item ) {
             if((""+item[key]).toLocaleLowerCase().includes(criteria.toLocaleLowerCase())){
                return true;
             }
           }
           return false;
        });
    }
}

    @Component({
      selector: 'sites-component',
      template: `
        <input #search  (keyup)="0">
        <ul>
          <li *ngFor="let site of (sites | searchFilter: search.value )">(...)</li>
        </ul>
      `
    })
    export class SitesComponent{
       sites : Array;
    }

dont't forget to declare the pipe in your module.

Upvotes: 7

Related Questions