0

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?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
Arvind
  • 21
  • 3
  • https://stackoverflow.com/questions/34417250/filtering-an-array-in-angular2 This can helps you. – John Doe Jun 07 '17 at 12:21
  • https://stackoverflow.com/questions/37003551/how-do-i-filter-an-array-with-typescript-in-angular-2 please check this will be helpful to you – Jackson Jun 07 '17 at 12:25
  • I need a code like if I type anything in the text box and an array list only has to show relevant rows.In angular it's very easy to implement – Arvind Jun 07 '17 at 12:34
  • AngularX does not come with a filter pipe as angularjs does because they perform poorly and prevent aggressive minification. But you can easily write your own Pipes if you want to. I'm not going to write the code for you but if you want a zero-effort solution, go for an NPM package like e.g. `ng2-filter-pipe`. – Nico Van Belle Jun 07 '17 at 13:01
  • I made a solution for this one nico.please refer this custom pipe for better results – Arvind Jun 07 '17 at 13:13
  • Thank you all for your suggestions – Arvind Jun 07 '17 at 13:13

1 Answers1

1

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)">
Arvind
  • 21
  • 3