Search code examples
angularsortingfilteringasp.net-mvc-custom-filter

Custom filter using Angular


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.


Solution

  • 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>