Goutham Harshith
Goutham Harshith

Reputation: 283

Search Exact String using custom pipe in Angular 8

I have created a custom pipe in order to filter my data. This is my pipe code

import { Pipe, PipeTransform } from '@angular/core';
  @Pipe({
  name: 'filterAll'
    })
  export class SpecialPipe implements PipeTransform {
    transform(value: any, searchText: any): any {
      if(!searchText) {
        return value;
      }
      return value.filter((data) => JSON.stringify(data).toLowerCase().includes(searchText) ); 
    }

  }

This filter is totally working well, but my requirement is to search the exact string. I have to return the values begins with my searchText (not included). I have also tried .startsWith(), which is also not working. Is there any way to achive this?

Upvotes: 0

Views: 693

Answers (1)

Suresh Reddy
Suresh Reddy

Reputation: 11

startsWith is what you're looking for.

Here's the working snippet:

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

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], filterdata: string): any[] {
    if (!items) return [];
    if (!filterdata) return items;
    filterdata = filterdata.toString().toLowerCase();
    return items.filter((it) => {
      return it.name.toLowerCase().startsWith(filterdata);
    });
  }
}

Working StackBlitz demo

Upvotes: 1

Related Questions