Autocomplete input using Angular 9

Introduction

I am going to show you how to give auto complete suggesstion when users search for something by typing in the input field.

Autocomplete allows users to have other suggested strings or values displayed on typing of the relevant text in the input field.

You have also seen when you start a search on Google or other search engines, you can find the information you are looking for using search predictions.

Search predictions are possible search terms you can use that are related to the terms you are typing and what other people are searching for.

Autocomplete is a feature in which an application predicts the rest of a word a user is typing. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.

Autocomplete speeds up human-computer interactions when it correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. The autocomplete is a normal text input enhanced by a panel of suggested options.

Prerequisites

Angular 9

How to create Angular project

Autocomplete Implementation

Let’s start writing the code for implementing auto complete using Angular.

I am going to use onKeyUp event of JavaScript to give suggesstion to the users on typing two chars in the input field.

We will use static data to show the search results on key up event. Ideally the data should come from database or external service or any other system.

We will start by creating a service type script file by executing the following command on cmd tool.

ng g s search

So we are creating a service class using the above command.

Next we will put JSON data (results.json file) under assets/data folder with the following content:

[
	"Lorem Ipsum is simply dummy text of the printing and typesetting",
	"Lorem Ipsum has been the industry's standard dummy",
	"nd scrambled it to make a type specimen book. It",
	"typesetting, remaining essentially unchanged. It ",
	"sum passages, and more recently with desktop publi",
	"Contrary to popular belief, Lorem Ipsum is not sim",
	"professor at Hampden-Sydney College in Virginia, looked up one",
	"passage, and going through the cites of the word in",
	"comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum",
	"BC. This book is a treatise on the theory of ethics, very popu",
	"here are many variations of passages of Lorem Ipsum availa",
	"believable. If you are going to use a passage of Lorem Ips",
	"middle of text. All the Lorem Ipsum generators on the Intern",
	"tend to repeat predefined chunks as necessary, making this the",
	"first true generator on the Internet. It uses a dictionary of over 20",
	"he standard chunk of Lorem Ipsum used since the 1500s i",
	"1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als",
	"reproduced in their exact original form, accompanied by English",
	"eadable content of a page when looking at its layout. The point"
]

Now add HttpClientModule and SearchService in app.module.ts file. The entire file looks similar to the below:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule }    from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { SearchService } from './search.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
	HttpClientModule
  ],
  providers: [SearchService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we will edit the search service and return the JSON data from the static JSON file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class SearchService {

	constructor(private http: HttpClient) { }

	getResultList() {
		const headers = new HttpHeaders({ 'Content-Type': 'application/json' })
        return this.http.get('./assets/data/results.json', { headers });
    }

}

Next we will modify the app.component.ts file to perform the search and return the results.

On key up event we perform the match of the input value with the JSON data and return those strings which have the similar text to the input value.

As a basic validation I am checking whether user has input at least two characters or not before showing the results.

import { Component, OnInit } from '@angular/core';

import { SearchService } from './search.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

	results: any[] = [];
	searchResults: any[] = [];
	
	constructor(private searchService: SearchService) { }
	
	ngOnInit() {
		this.getSearchResults();
	}
	
	getSearchResults(): void {
		this.searchService.getResultList().subscribe(sr => {Object.assign(this.searchResults, sr);});
	}
	
	searchOnKeyUp(event) {
		let input = event.target.value;
		//console.log('event.target.value: ' + input);
		//console.log('this.searchResults: ' + this.searchResults);
		if (input.length > 1) {
			this.results = this.searchFromArray(this.searchResults, input);
		}
	}  

	searchFromArray(arr, regex) {
		let matches = [], i;
		for (i = 0; i < arr.length; i++) {
			if (arr[i].match(regex)) {
				matches.push(arr[i]);
			}
		}
		//console.log('matches: ' + matches);
		return matches;
	};

}

Finally we create the HTML part into app.component.html file:

<router-outlet></router-outlet>

<label>Search Here</label>&nbsp;&nbsp;<input type="text" (keyup)="searchOnKeyUp($event)" list="SearchResults" />
<datalist id="SearchResults">
   <option *ngFor="let sr of results" [value]="sr">{{sr}}</option>
</datalist>

Testing the Application

Run the application by executing the command ng serve --open in cmd tool.

You application opens at http://localhost:4200 in the system’s default browser. You will see an input box with label Search Here.

When you type, for example, he, you will get the following result:

auto complete input using angular

That’s all about how to implement autocomplete search box in Angular.

Source Code

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *