search pipe after 2 letters in angular4

1.7k views Asked by At

I have seacrh pipe it's working fine, problem is it's search after i type full word, I want to seacrh after two lettrs of input this is the code

<input type="text" class="form-control"   [value]="searchRole"/>
<li *ngFor="let user of roleUserData | SearchRolePipe: 'name':searchRole ;let  i= index" >{{user.name}}</li>

export class SearchRolePipe implements PipeTransform {


  transform(items: any[], field: string, value: string): any[] {

    if (value === '') {
      return items
    }
     if (!items) {

       return [];
     } else {

      return items.filter(it => it[field] == value);
}
}

it's working , my requiremnet is it should search after 2 letters of user input

example if array is like

[
{'name': 'abc'}, 
{'name': 'abcde'},
{'name': 'bce'}

] Here searchRole is empty public variable if i am going to search abc then only it giving back result [{name: abc}]

But I want if I type 'ab' then it should return

[
 {'name': 'abc'}, 
    {'name': 'abcde'}]

please any one let me know how to solve it or any other good approach

3

There are 3 answers

0
hagner On

I think this is what you want:

transform(items: any[], field: string, value: string): any[] {

    if (!items) {
        return [];
    }

    if (!value || value.length === 0) {
      return items;
    } 

    return items.filter(it => it[field].indexOf(value) >= 0);
}
2
brijmcq On

Try this

transform(items: any[], field: string, value: string): any[] {

    if (value === '') {
      return items
    }
     if (!items) {

       return [];
     } else if( value.length >= 2 ) { //new code here
      return items.filter(it => it[field] == value);
     }else{
      return items; // returning all the items. Filtering starts at 2 letters
     }
0
Omar Hasan On

this will do what you want

// imports in top level  
    import { of, pipe } from 'rxjs';
    import { map, filter } from 'rxjs/operators';
// imports in top level 

const namesArray = of('omar', 'ali', 'tota', 'lelo', 'pedo')
.pipe(filter((n: any) => n.indexOf('o') >= 0)); // get names containing letter "o"
namesArray.subscribe(x => console.log('filter,map ', x));