1

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) :

4
  • I think you forgot to post your code. Commented Dec 21, 2018 at 7:34
  • @HaseebAhmed Sir, Can you please check now. Commented Dec 21, 2018 at 7:36
  • Are you looking for exact matches or if it only contains than show that as well? Commented Dec 21, 2018 at 8:15
  • I'm looking for exact match sir Commented Dec 21, 2018 at 8:26

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

7 Comments

Sir, I'm getting the following error. I've attached a log to my question.
Sir, I've imported the @Injectable and tried to log the value on the console and i have attached the copy of my log above. Please look.
So value is not undefined. Do a console.log(items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()))). And this one too console.log(items.filter(singleItem => singleItem[field].toLowerCase() == value.toLowerCase()))
I believe you are trying to filter based on CampaignName. console.log(field) to make sure you are getting that correct.
I did a console log of field. Please check the link above.
|
0

Pipe file

filteredItems: Array<any>;
// Items & searchText is the input of the pipe;
// @param: Items contains current object in the ngFor loop.
// @param: searchText is the text that is need to be searched string.


transform(items: any[], searchText: string): any[] {

    if (!items) {
        return [];
    }
    if (!searchText) {
        return items;
    }
    searchText = searchText.toLowerCase();
    this.filteredItems =  items.filter( function (records) {
        let searchMatched;
        for ( const keys in records ) {
            if ( typeof (records[keys]) === 'string') {
                searchMatched = records[keys].toLowerCase().includes(searchText);
                if (searchMatched) {
                    return searchMatched;
                }
            }
        }
    });

    if (this.filteredItems.length < Constants.ONE_COUNT) {
        return -1;
    } else {
        return this.filteredItems;
    }
}

Returning the -1 in the last second line is to handle the zero results found.

HTML File

*ngFor="data| searchFilter: inputText;

The above code will do the case-insensitive search if you want to implement case sensitive search please remove the conversion of search text to lowercase

Comments

0

in your pipe .ts

 @Pipe({
  name: 'nameFilter'
})

export class NameFilterPipe implements PipeTransform {
  transform(values: any, key?: string): any[] {
    debugger;
    if (!key) return values;
    key = (key.trim()).toLowerCase();
    return values.filter(val => (val.CampaignName).toLowerCase() === key);
  }
}

and in your .html

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

here is a link of working example of stackblitz

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.