Search code examples
angularangular6angular-pipe

Implementing search using custom pipe in angular


I tried implementing my own pipe in angular 6 using search box for filtering the list of my campaigns. Oddly, I'm unable to filter the the list of campaigns. I'm posting my code down below.

This is how my filter looks like:

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

@Pipe({
  name: 'nameFilter'
})

export class NameFilterPipe implements PipeTransform {
  transform(values: any[], key: string, value: string): any[] {
    debugger;

    if (!values) {
      return [];
    }
    if (!value) {
      return values;
    }
    return values.filter(val => val.CampaignName === value);
  }
}
<input [(ngModel)]="searchText" placeholder="search here">

<tr *ngFor="let campaign of campaigns?.result | nameFilter : searchText">

  <td style="max-width:280px">
  
    <p>{{campaign.CampaignName}}</p>
    
    <small><span class="cursor" (click)="filterByOwnr(campaign.DepartmentName)" > {{ campaign.DepartmentName }} &nbsp; &nbsp; </span></small>
    
  </td>

I debugged my pipe, and this is how it looks like:

Debug window for pipe

I am able to get the value to my pipe but unable to apply filter in my html page.

P.S : After trying @Arcteezy , i'm getting the following error.

enter image description here

Console log for console.log(field) :


Solution

  • Try this,

        import { Pipe, PipeTransform, Injectable } from '@angular/core';
    
        @Pipe({
            name: 'filter'
        })
    
        @Injectable()
        export class FilterPipe implements PipeTransform {
            transform(items: any[], field: string, value: string): any[] {
    
                console.log(value);
                if (!items) {
                    return [];
                }
                if (!field || !value) {
                    return items;
                }
    
                return items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()));
            }
        }
    

    In your HTML,

        *ngFor = "let... | filter : '<search_field>' : searchText"