Creating An Autocomplete Textbox In Angular

In this, we will learn how to create an autocomplete textbox in Angular 4 using Typescript.

Introduction

I have seen in some web crawlers and sites that while I am writing the initial two letters of a word, it demonstrates a recommended run down to choose. These auto-finish content boxes are for the most part utilized as a part of ongoing tasks to expand client intuitiveness with the site. Presently, in this post, we will take a gander at how this is executed in Angular4 using TypeScript.

For instance, we should discuss the Google auto-finish look box. Here, the proposed results will come in view of the past list items or most looked outcomes.

Executing Auto Complete Textbox in Angular
 
To execute an auto-finish content box in Angular with a textbox, we need to create an Angular application. In this application, I am getting the information recommendation from the service. Here are some references which can help you make and configure Angular project.
Steps to complete auto-complete text box task include - 

First of all, you need to install node.js and VS code on your system. Create an Angular application using Angular CLI command. If you are still facing issues to create a simple "Hello world" application with all configurations, click here...
 
Follow some steps to create autocomplete textbox using Angular.
 
Step 1

Create ASP.NET WEBAPI to get data from database. Now, I am getting clientList from API. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace ApplicationAPI.Controllers  
  9. {  
  10.   
  11.     [RoutePrefix("api/Client")]  
  12.     public class ClientController : ApiController  
  13.     {  
  14.         MVCRSTechEntities _context = new MVCRSTechEntities();  
  15.         [Route("GetClientList/term")]  
  16.         public IHttpActionResult GetClientList(string term)  
  17.         {  
  18.             var clientList = from c in _context.Clients  
  19.                              where c.ClientName.Contains(term)  
  20.                              select c;  
  21.             return Ok(clientList);  
  22.         }  
  23.     }  
  24. }  
So now, I am consuming endpoint http://localhost:52386/api/Client/GetClientList/term?term=a.
 
 
 
If you don't want to waste your time to create API, just use this JSON to get the client list according to any string word. Save this JSON in your project name as Client.josn and set path inside http.get() method.
 
Client.Json 
  1. [  
  2.     {  
  3.         "ClientId": 11,  
  4.         "ClientName""Hytech Professionals"  
  5.     },  
  6.     {  
  7.         "ClientId": 12,  
  8.         "ClientName""RVS IT Consulting"  
  9.     },  
  10.     {  
  11.         "ClientId": 13,  
  12.         "ClientName""MCN Solution"  
  13.     },  
  14.     {  
  15.         "ClientId": 24,  
  16.         "ClientName""C# Corner"  
  17.     },  
  18.     {  
  19.         "ClientId": 27,  
  20.         "ClientName""Birla sunlife"  
  21.     },  
  22.     {  
  23.         "ClientId": 28,  
  24.         "ClientName""Global Logic"  
  25.     }  
  26. ]  
Otherwise, you can use the API to get data from the database. Here, both the options are avilable -  you can choose any API or JSON directly.
 
Step 2

Create an Angular application using  Angular-CLI (ng new project_name) with a single line of command.
 
Step 3

In Angular, the default application replaces app.component.html. See code below,
 
src=>app=>app.component.html 
  1. <label class="col-sm-4 col-md-8 text-right control-label vertical-label" for="inputPassword3"> Select Client Name</label>  
  2. <div class="col-sm-8 col-md-4 text-right">  
  3.     <div class="form-group">  
  4.         <div class="input-group">  
  5.             <input class="form-control" *ngIf="flag" type="text" [(ngModel)]="ClientName" (keyup)="searchClient(ClientName)" />  
  6.             <input class="form-control" [(ngModel)]="ClientName" disabled *ngIf="!flag" type="text" />  
  7.               
  8.         </div>          
  9.     </div>  
  10.     <div class="search-result" *ngIf="flag">  
  11.         <ul>  
  12.             <li *ngFor="let client of clients | async">  
  13.                 <a (click)="onselectClient(client)">{{client.ClientName}}</a>  
  14.             </li>             
  15.         </ul>  
  16.     </div>  
  17.   
  18.   
  19. </div>  
 In HTML part, I have created a textbox and applied changes to create autocomplete textbox accordingly.
 
Step 4

Use app.component.ts to write logic. Just replace the code with the following.
 
src=>app=>app.component.ts
  1. import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';  
  2. import { Observable, Subject } from 'rxjs';  
  3. import { ClientSearchService } from './_services/client-search.service';  
  4. @Component({  
  5.   selector: 'client-search',  
  6.   templateUrl: './app.component.html',  
  7. })  
  8. export class AppComponent implements OnInit {  
  9.   public clients: Observable<any[]>;  
  10.   private searchTerms = new Subject<string>();  
  11.   public ClientName = '';  
  12.   public flag: boolean = true;  
  13.   constructor(  
  14.     private clientSearchService: ClientSearchService,  
  15.   ) {  
  16.   
  17.   }  
  18.   
  19.   ngOnInit(): void {  
  20.     this.clients = this.searchTerms  
  21.       .debounceTime(300)        // wait for 300ms pause in events  
  22.       .distinctUntilChanged()   // ignore if next search term is same as previous  
  23.       .switchMap(term => term   // switch to new observable each time  
  24.         // return the http search observable  
  25.         ? this.clientSearchService.search(term)  
  26.         // or the observable of empty heroes if no search term  
  27.         : Observable.of<any[]>([]))  
  28.       .catch(error => {  
  29.         // TODO: real error handling  
  30.         console.log(error);  
  31.         return Observable.of<any[]>([]);  
  32.       });  
  33.   }  
  34.   // Push a search term into the observable stream.  
  35.   searchClient(term: string): void {  
  36.     this.flag = true;  
  37.     this.searchTerms.next(term);  
  38.   }  
  39.   onselectClient(ClientObj) {     
  40.     if (ClientObj.ClientId != 0) {  
  41.       this.ClientName = ClientObj.ClientName;       
  42.       this.flag = false;  
  43.     }  
  44.     else {  
  45.       return false;  
  46.     }  
  47.   }  
  48.   
  49. }  
Step 5

Create Service folder name is _services => client-search.service.ts and inside this TS file, write the code to consume WebAPI.
 
src=>app=>_services=>client-search.service.ts 
  1. import { Injectable } from '@angular/core';  
  2. import { Http, Response } from '@angular/http';  
  3. import { Observable } from 'rxjs';  
  4. @Injectable()  
  5. export class ClientSearchService {  
  6.     endPoint: string;  
  7.     constructor(private http: Http) {  
  8.         this.endPoint = "http://localhost:52386/api/Client/GetClientList/term";  
  9.     }  
  10.     search(term: string): Observable<any[]> {  
  11.         var ClientList = this.http.get(this.endPoint + '?term=' + term)  
  12.             .map((r: Response) => { return (r.json().length != 0 ? r.json() : [{ "ClientId": 0, "ClientName""No Record Found" }]) as any[] });  
  13.         return ClientList;  
  14.     }  
  15. }  
Step 6

Now, we need some changes in app.module.ts. We need to register service in provider.
 
src=>app=>app.module.ts 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { FormsModule } from '@angular/forms';  
  3. import { NgModule } from '@angular/core';  
  4. import { HttpModule } from '@angular/http';  
  5. import { ClientSearchService } from './_services/client-search.service';  
  6. import { AppComponent } from './app.component';  
  7.   
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule, FormsModule, HttpModule  
  14.   ],  
  15.   providers: [ClientSearchService],  
  16.   bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule { }  
Step 7

To make it more attractive, use CSS. Copy this code and paste it on index.html page.To add CSS file, download the project from this article.
 
src=>index.html 
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <meta http-equiv="x-ua-compatible" content="ie=edge">  
  6.   <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />  
  7.   <!-- Bootstrap 3.3.6 -->  
  8.   <link href="/assets/css/bootstrap.min.css" rel="stylesheet" />  
  9.   <link href="/assets/css/custom.css" rel="stylesheet" />  
  10.   <!-- Theme style -->  
  11.   <link href="/assets/css/AdminLTE.css" rel="stylesheet" />  
  12.   <!-- icon font -->  
  13.   <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />  
  14.    
  15.   <link href="/assets/css/skins/_all-skins.min.css" rel="stylesheet" />   
  16.   <link rel="shortcut icon" href="assets/img/favicon.ico">  
  17.   <link rel="icon" type="image/gif" href="assets/img/animated_favicon1.gif">  
  18. </head>  
  19. <body>  
  20.   <client-search></client-search>  
  21. </body>  
  22. </html>  
You can see here on the index.html, I am using component client-search  as tag.
 
Step 8

I think we are all set to run the application but be sure, you've installed all packages from npm. If not, use command "npm install"  after npm which will create a new folder in your root folder with the name  "node_module".
 
Step 9

Now, we are ready to run the application. Open the termiinal and run command "npm start" or "ng serve".
 
Step 10

Remember if Chrome browser is not opening by default, type http://localhost:4200/. You'll see output in your browser like this.
 
 
Conclusion
 
According to this image type, any word or character in the textbox result will show. Data is coming from database according to search word 's'. I hope, your application is working and I am sure you learned a simple trick to make the textbox auto-complete using Angular and TypeScript. If you are still facing any error or issue, download the attached project.