0
votes

I'm trying to set up a dynamic research with Angular 7. I'm fetching an array from my API with multiple keys : [ _id => 123, pseudo => "Germain", email => .. ]. I need to filter all my results with a string but only on my pseudo field and then returns all the array with only the matching values.

I display all my results with ngFor and I've already created a filter pipe with a tutorial that I've found..

Here is my research component :

<div *ngFor="let profil of profils | filter : searchText" class="col-md-4">
                <figure class="card card-product">
                    <img class="rounded-circle w-50 mx-auto" src="https://i.ibb.co/PQfsPbH/profil.jpg">
                    <figcaption class="info-wrap">
                        <h4 class="title">{{ profil.pseudo }}</h4>
                        <p class="desc">{{ profil.desc }}</p>
                        <div class="rating-wrap">
                            <div class="label-rating">132 reviews</div>
                        </div>
                    </figcaption>
                    <div class="bottom-wrap">
                        <a [routerLink]="['personnalite', profil._id]" class="btn btn-sm btn-primary float-right">Voir le profil</a>
                    </div>
                </figure>
            </div>

And here is my filter pipe function :

export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items; 
    searchText = searchText.toLowerCase();
    return items.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}

But this will filter only arrays like this : [ "pseudo1", "pseudo2"..] and not indexed ones... Any idea how to manage this ?

1

1 Answers

2
votes

export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items; 
    searchText = searchText.toLowerCase();
    //updated
    return items.filter( item => item.pseudo.toLowerCase().indexOf(searchText) > -1 ); 
   }
}

It will return an array with matched array items.

Hope it helps :)