circuit

How to Implement an Instant Search Functionality in Angular

How to display instant search results as a user types




Photo by Markus Winkler on Unsplash

Photo by Markus Winkler on Unsplash

Introduction

An instant search is a feature that allows you to display results as a user types in the search query. This helps enhance user experience because the user does not have to wait, long, before the search results are displayed.

In this guide, I will show you how you can use one of Angulars' most powerful features namely pipe to implement an instant search. The Angular application that we will implement will search for programming languages from some data source.

Getting started

If you do not already have an Angular application, but want to follow along, you can easily create one with the following command. I have named my application instant-search, but feel free to use any name of your choice.

$ ng new instant-search --defaults

We will start by creating the user interface for inputting the search. Now, go to the app.component.html and remove all the template code and replace it with the code below.

<section>
    <h5> Dynamic search results </h5>
    <input name="searchInput" type="text" placeholder="Search for programming languages" size="50">
</section>

The code above is pretty simple, we create a header title and then create an input field. The input field is where you can type the programming language you are looking for. In addition, the input has some placeholder text.

At this stage, the user interface should now look as below. That is all we need basically.

To serve the Angular application, run the following command from the applications' root folder.

$ ng serve

Update the component logic

For simplicity, our data source will be a hard-coded array of programming languages, but it could be anything really.

In the app.component.ts file, we will create the array of programming languages from which we will search. In addition, we will create a property named searchInput of type string.

Update your app.component.ts with the code that is in bold as below.

export class AppComponent {
    title = 'instant-search';

    public searchInput: string;
    public programmingLanguages = [
      'Python','TypeScript','C','C++','Java',
      'Go','JavaScript','PHP','Ruby','Swift','Kotlin'
   ]
}

Create an Angular pipe

As mentioned earlier, the search functionality will be built on top of an Angular pipe. Basically, an Angular pipe takes in some data input and returns data that is formatted or transformed according to the instructions of the pipe.

Create a file named search.pipe.ts. To keep things simple, I have placed the pipe file in the same root folder that holds the app.component.ts file. Your folder structure should now look as follows.

Copy the code below and paste it into the newly create search.pipe.ts file. I have named the pipe search; this is the name that we will use when referring to the pipe in the template.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name:'search'
})

export class SearchPipe implements PipeTransform {
    transform(languages: string[], searchInput: string): any[]{
        if(!searchInput) {
            return  [];
        }

       searchInput = searchInput.toLowerCase();
       return languages.filter(
           x =>x.toLowerCase().includes(searchInput)
       )
     }
}

The pipe logic above gets an array of all the programming languages from our data source, and returns an array of the programming languages that match the input text as you type.

If there is no input text, it will return an empty array, meaning there will be nothing to display.

Also, note that we change all input text to lowercase to make sure that a proper match is gained.

Add assets to the main module file

To be able to use the pipe in other components, it must be registered in the app.module.ts file. In addition, also import the FormsModule as in the code below. The code to be added to the app.module.ts file is in bold as below.

import { SearchPipe } from './search.pipe';
import { FormsModule } from '@angular/forms';

declarations: [
  AppComponent,
  SearchPipe
],

imports: [
   BrowserModule,
   FormsModule
]

Update the template code

Finally, we need to update the template code so that we can search and display the corresponding results using the pipe.

Update the app.component.html file with the code that is in bold.

<section>

 <h5> Dynamic search results </h5>

<input name="searchInput" [(ngModel)]="searchInput" type="text"  placeholder="Search for programming languages" size="50" >

    <article>
        <h6> Results </h6>
        <ul>
          <li *ngFor="let programmingLanguage of
                        programmingLanguages | search: searchInput">
             {{programmingLanguage}}
          </li>
        </ul>
    </article>
</section>

I have added an article section for displaying the search results. The pipe filters the programming languages based on the search input.

The search in action

If you have followed along properly, you should now have a working instant-search functionality.

Go to the browser page where your application is being served and type a name of the programming languages that is in our array. You should get similar output to the one below.

Conclusion

There you have it, a dynamic search that displays instant search results as we type.

We have built our search on top of an Angular pipe, which is a well tested and robust functionality that Angular provides out of the box.




Continue Learning