PolarDog
PolarDog

Reputation: 33

How to create a functional Search Bar in Ionic 4?

I'm currently developing a small Ionic 4 project for college that uses Google Firebase to save and store data, which will be used by the nursing course / class to make things easier for them when it comes to saving patients' data and test details.

In the page that shows all registered patients, I have an ion-searchbar which will be used to filter the patients by name and a ng-container with a *ngFor that pulls all registered patients from the database and puts them into ion-cards.


<ion-searchbar placeholder="Search..." expand="full" color="abwb" [(ngModel)]="searchQuery" (ionChange)="search()"></ion-searchbar>

<ng-container *ngFor="let patient of dBase">

    <ion-card color="abwb">
      <ion-card-header style="font-weight: bold">{{patient.name}}</ion-card-header>
      <ion-card-content>
        <ion-button [routerLink]="['/pat-prf', patient.id]" color="bwab">PROFILE<ion-icon name="person" slot="start"></ion-icon></ion-button>
        <ion-button [routerLink]="['/pat-tst', patient.id]" color="bwab">TESTS<ion-icon name="list-box" slot="start"></ion-icon></ion-button>
      </ion-card-content>
    </ion-card>

</ng-container>

I managed to get the value from what's being typed into the search field to be displayed via a console.log() action, but I have no idea on how to make it actually go and search the database for the specified names OR to make the ng-container only show the cards with names that match.

I've been told I had to use a *ngIf to do such a thing, but I honestly got no idea how to use it properly for this kind of thing. Can anyone point me in the right direction?

Upvotes: 1

Views: 1816

Answers (1)

yazantahhan
yazantahhan

Reputation: 3110

You have two solutions, a Frontend solution and a Backend solution.

The Frontend solution

The frontend is to filter out the list that you have from the server. This is can use the Array.prototype.filter(). In order to make this work, the backend should return all the patients without pagination (Which can work for small list, but not preferred for big one).

// allPatients will contain all the results from the server and dBase will be filtered
private allPatients = [];

ngOnInit() {
   this.httpClient.get(MY_API_TO_GET_PATIENTS)
    .subscribe(response => this.allPatients = this.dBase = response )
}

search() {
  this.dBase = allPatients.filter(item => item.name.includes(this.searchQuery));
}

The Backend solution

In this solution, we will send a request to the Backend that contains the search query. Then, the Backend will respond with the results that met the search query. Here we will need only to send a new request to the server each time the user enters a new value.

search() {
  this.httpClient.get(MY_URL, {params: {searchQuery: this.searchQuery})
    .subscribe(response => this.dBase = response )
}

Upvotes: 1

Related Questions