Custom filter using Angular

10.7k Views Asked by At

I have a list of text fields that needs a custom filter.

Suppose when the user searches with a specific string/character, the app has to show only that records in the table view.

2

There are 2 best solutions below

0
On BEST ANSWER

Here list which is in the grid Here is the list which is in the grid

After using the pipe (custom filter) After using the pipe (custom filter)

This can be achieved by using custom filter in angular , first we have create a pipe using (ng g pipe filterName), navigate to pipe component which u generate and make use of transform method, here is the transform method i used

transform(items: any, a: string, b: string, c: string){
if (items && items.length){
    return items.filter(item =>{
        if (a&& item.name.toLowerCase().indexOf(a.toLowerCase()) === -1){
            return false;
        }
        if (b && item.industry.toLowerCase().indexOf(b.toLowerCase()) === -1){
            return false;
        }
        if (c&& item.location.toLowerCase().indexOf(c.toLowerCase()) === -1){
            return false;
        }
        return true;
   })
}
else{
    return items;
}

} then navigate to particular html where u gonna use custom filter

<input type="text" [(ngModel)]="a">
<input type="text" [(ngModel)]="b">
<input type="text" [(ngModel)]="c">
<div *ngFor="let item of data | customFilter :a:b:c">
  {{item.{{item.city}}}}
</div>
0
On

You could write an Angular pipe (https://angular.io/guide/pipes) to transform your list.

Example:

ng generate pipe filter

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

@Pipe({
  name: 'filterPipe'
})
export class FilterPipe implements PipeTransform {

  transform(textFields: string[], searchWord: string): any {
    return textFields.filter(val => val.toLowerCase().includes(searchWord));
  }

}

<ul>
    <li *ngFor="let field of textFields | filterPipe : searchWord"></li>
</ul>