Arvind
Arvind

Reputation: 21

How to make array search filter in angular2?

I create a text box and an array. I want to filter array items according to the text box value.

 <div class="searchboxt"> <input type="text" placeholder="Search Tickets" 
 class="searchboxttext" [(ngModel)]="searchfav"/> </div>
 <li class="selectlistticket" *ngFor="let fav of (favlist.slice().reverse() 
 | SearchfilterPipe: searchfav)" (mouseover)="showfavstar(fav)" (mouseleave)
 ="hidefavstar(fav)">

How do I filter an array in angular2?

Upvotes: 0

Views: 1562

Answers (1)

Arvind
Arvind

Reputation: 21

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

@Pipe({
  name: 'searchfilter',
  pure: false
})
export class SearchfilterPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }
}

This works 100% fine like I expected. Save this as pipe and import this in both appmodule and your component.

   
     <div class="searchboxt"> <input type="text" placeholder="Search Tickets" class="searchboxttext" [(ngModel)]="searchfav"/> </div>

   <li class="selectlistticket" *ngFor="let fav of favlist.slice().reverse() | searchfilter :searchfav" (mouseover)="showfavstar(fav)" (mouseleave)="hidefavstar(fav)">

Upvotes: 1

Related Questions