Angular - How to filter (search) data from multiple properties of data (fields)?

5.9k Views Asked by At

I'm getting my data through API. I want to create filtering and searching on the data. I've created a pipe and it has the following code:

File: text-search.pipe.ts

transform(items: any[], searchText: string): any {
    if (!items) return [];

    if (!searchText) return items;
    console.log("ITEMS ARE",items);
    searchText = searchText.toLowerCase();


    return items.filter(it => {
        return it.hospital_name.toLowerCase().includes(searchText);
    });

  }

My component.html file is as follows:

The input field //User can search by name

 <input type="text" [(ngModel)]="searchText" class="form-control" placeholder="Search">

And then the pipe is applied to:

 <div class="col-lg-3 col-md-4 col-sm-6" *ngFor="let hospital of hospital_list | hospitalSearch: searchText; let i = index;">

Question: If I have another input field or several other fields such as City Field where the user can search through City, Specialization etc as well?

For e.g. :

 <input type="text" [(ngModel)]="searchCity" class="form-control" placeholder="Search">

So how do I modify the existing pipe? Or would I have to create a new pipe.

Things I've tried: In pipe.ts file:

transform(items: any[], searchText: string, searchCity?: string): any {
    if (!items) return [];

    if (!searchText) return items;
    console.log("ITEMS ARE",items);
    searchText = searchText.toLowerCase();

    if (!searchCity) return items;
    console.log("ITEMS ARE",items);
    searchCity= searchCity.toLowerCase();


    return items.filter(it => {
        return it.hospital_name.toLowerCase().includes(searchText);
        return it.hospital_city.toLowerCase().includes(searchCity);

    });

It doesn't work since the 2nd return statement is un-reachable. I have tried to read the API I didn't find any support. Kindly guide me how to add multiple field search filtering to the data I'm getting. Thank You. }

1

There are 1 best solutions below

1
On

Use a boolean operator here. You will need to choose which one is most appropriate for your particular filtering use case.

Filter items that match at least one of:

return items.filter(it => {
    return it.hospital_name.toLowerCase().includes(searchText)
        || it.hospital_city.toLowerCase().includes(searchCity);
});

Filter items that match all:

return items.filter(it => {
    return it.hospital_name.toLowerCase().includes(searchText)
        && it.hospital_city.toLowerCase().includes(searchCity);
});

To invoke your pipe with multiple arguments, use another :.

*ngFor="let hospital of hospital_list | hospitalSearch: searchText:searchCity"