bilados
bilados

Reputation: 65

How to pipe search all data no only name? Angular

I made a pipe that works well, but searches only the name. I want to search for more parameters, including: population, region and capital. Check my code:

    <div class="card d-flex flex-direction-column"
        *ngFor="let country of countries | country:searchTerm; let i=index">
        <img [src]="country.flag" alt="flag icon" style="width:100%">
        <div class="text-content white">
            <h4><b>{{ country.name }} </b></h4>

            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Population:&nbsp;</p> <span class="font-w-200">{{ fixNum(country.population) }}</span>
            </div>
            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Region:&nbsp;</p> <span class="font-w-200"> {{ country.region }} </span>
            </div>
            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Capital:&nbsp;</p> <span class="font-w-200"> {{ country.capital }} </span>
            </div>
        </div>
    </div>

and most important PIPE

export class CountryPipe implements PipeTransform {

  transform(country:any, searchTerm: string): HomeComponent { 
    if (!country || !searchTerm) {
      return country;
    }
    return country.filter(country =>
      country.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
  }

}

Upvotes: 2

Views: 306

Answers (2)

Aaron Psujek
Aaron Psujek

Reputation: 11

Rather than simply passing in a single string as a parameter to the pipe, you can pass an object that contains the values you wish to check your array against. The implementation provided in the below stackblitz is pretty ugly, but highlights how this can be accomplished in a minimal way.

https://stackblitz.com/edit/angular-4czmjr?file=src/app/sample.pipe.ts

Also, your pipe appears to be returning an array rather than a component as the return type would imply.

Upvotes: 1

Bansi29
Bansi29

Reputation: 1079

Try Below way I hope it work.

 export class CountryPipe implements PipeTransform {

     transform(country:any, searchTerm: string): HomeComponent { 
        if (!country || !searchTerm) {
            return country;
        }
     return country.filter(country =>
          country.name.toLocaleLowerCase().replace(/ /g, '').includes(searchTerm.toLocaleLowerCase().replace(/ /g, ''))
      || country.population.toLocaleLowerCase().replace(/ /g, '').includes(searchTerm.toLocaleLowerCase().replace(/ /g, ''))
      || country.region.toLocaleLowerCase().replace(/ /g, '').includes(searchTerm.toLocaleLowerCase().replace(/ /g, ''))
      || country.capital.toLocaleLowerCase().replace(/ /g, '').includes(searchTerm.toLocaleLowerCase().replace(/ /g, ''))
      );
   }

}

Upvotes: 0

Related Questions