Angular | Simple TypeAhead Autocomplete Suggestion Search implementation in Angular 6+ Applications

In this tutorial, we will implement a very simple Autocomplete feature which is also known as TypeAhead or Suggestion search bar. Typeahead is basically an Input field where user can type and get matching results in a dropdown list to select from.

Adding a suggestion or Autocomplete field is useful where we have a large data to show up which can’t we be accommodated in tradition select dropdowns. Autocomplete lists really optimize DOM structure by preventing a dump of large data on the client-side.

We already discussed Autocomplete using Angular Material and Bootstrap but if there is a quick need of time and we don’t want to get into large libraries integration then NgxTypeahead solves the purpose very well.

Let’s get started!

First, we will start with a new Angular project here build using the latest Angular CLI version v7.3.8. You can have the latest version of Angular CLI check this tutorial on updating it.

$ ng new NgxTypeaheadDemo

Install Ngx-TypeAhead NPM package

$ npm install ngx-typeahead --save-dev

Import NgxTypeaheadModule in the app.module.ts file as shown below

//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

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

import { NgxTypeaheadModule } from 'ngx-typeahead';

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

Theme styling is easy with bootstrap as Typeahead was originally created by Twitter. Just add the bootstrap.css file in index.html

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Or you can simply add following CSS style in the styles.css file

.ta-results.list-group{
    max-width: 400px;
    overflow: auto;
    max-height: 75vh;
    border: 1px solid #ccc;
}
.typeahead-wrap .list-group-item {    
    width:100%;
    text-align: left;
    position: relative;
    display: block;
    padding: 5px 10px;
    margin-bottom: -1px;
    background-color: #fff;
    border: 1px solid rgba(0,0,0,.125);
}

.typeahead-wrap .list-group-item{
    width:100%;
    text-align: left;
}
.typeahead-wrap .list-group-item.active{
    background-color: #ccc;
}

.typeahead-wrap .list-group-item .item-name {
    font-weight: bold;
}

 

Next, adding typeahead in the application is very easy.

Simple Typeahead with Local Data List

In the component template, add the following Input form field control with ngxTypeahead directives and some other required attribute properties.

<input [value]="search1"
        ngxTypeahead
        [taList]="myLocalList" 
        (taSelected)="selectedStatic($event)">

[taList]: Items data list which will populate when a user types.

(taSelected): Emit event when an item from suggestions is selected.

In the app.component.ts file add the following code

//app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'NgxTypeahead Demo';

  // Typeahead with Local Data List

  public myLocalList = [
    "Burgers",
    "Sandwiches",
    "French Fries",
    "Milkshakes",
    "Taco",
    "Biscuit",
    "Cookies",
    "Hot Dog",
    "Pizza",
    "Pancake"
  ];
  public search1 = '';
  selectedStatic(result) {
    this.search1 = result;
  }
}

Typeahead with Custom Template

If you have a list of an object then we show custom suggestion list using Angular's ngTemplate directive as shown below.

<input [value]="search2"
        ngxTypeahead
        [taList]="myLocalDataList" 
        [taItemTpl]="myTemp"
        (taSelected)="selectedTempStatic($event)">
[taItemTpl]: Takes the template variable defined on <ng-template></ng-template>
And custom template as follows
      <ng-template #myTemp let-item>
        <div class="item-name">
          {{item.result.name}}
        </div>
        <div class="item-desc">
          {{item.result.description}}
        </div>
      </ng-template>

In component class, add the following object myLocalDataList with on select event handler selectedTempStatic().

  // Typeahead with Local Data List using Custom Template

  public myLocalDataList = [
    {
      name: "Burgers", 
      description: "A flat round cake of minced beef that is fried or grilled and typically served in a bread roll; a hamburger."
    }, {
      name: "Sandwiches", 
      description: "an item of food consisting of two pieces of bread with a filling between them, eaten as a light meal."
    }, {
      name: "French Fries", 
      description: "French fries, or simply fries; chips, finger chips, or french-fried potatoes are batonnet or allumette-cut deep-fried potatoes"
    }, {
      name: "Milkshakes", 
      description: "a cold drink made of milk, a sweet flavouring such as fruit or chocolate"
    }, {
      name: "Taco", 
      description: "a Mexican dish consisting of a folded or rolled tortilla filled with various mixtures, such as seasoned mince, chicken, or beans."
    }, {
      name: "Biscuit", 
      description: "a small baked unleavened cake, typically crisp, flat, and sweet."
    }, {
      name: "Cookies", 
      description: "a sweet biscuit."
    }, {
      name: "Hot Dog", 
      description: "The hot dog or dog is a grilled or steamed link-sausage sandwich where the sausage is served in the slit of a partially sliced bun."
    }, {
      name: "Pizza", 
      description: "Pizza is a savory dish of Italian origin."
    }, {
      name: "Pancake", 
      description: "A pancake is a flat cake, often thin and round, prepared from a starch-based batter that may contain eggs, milk and butter."
    }
  ];

  public search2 = '';

  selectedTempStatic(item) {
    this.search2 = item;
  }

Server Side request for Typeahead suggestions

In real-world applications, we always an API endpoint to get results to show in suggestions as a user types the query.
NgxTypeahead neatly handles server-side responses with debounce feature already added which earlier we added using custom RxJS operators in Angular Material Autocomplete.
In template add following Input control
      <input [value]="search3" 
      ngxTypeahead 
      [taUrl]="remote_API_url"
      [taParams]="params"
      [taItemTpl]="myAPIrespTemp"
      (taSelected)="selectedAPITempStatic($event)"
    >

Here we have  following  properties

[taUrl]: URL of remote API url/ end-point to get results.

[taParams]: Parameters which will be sent with the above API request.

In component, class add the following

  //Server side response in Typeahead suggestions
  public url = 'example.com/api/getfoods/json';
  public search3 = '';
  public params = {
    token: 'APP-TOKEN',
    something:'foo',
    query:this.search3
  };

  public selectedAPITempStatic (result) {
    this.search3 = result;
  }

For adding Debounce for server request add [taDebounce] property. Debounce prevents multiple API calls on every keypress and only make calls if the next keypress event is fired after a given time value.

Conclusion: NgxTypeahead package is a stand-alone Autocomplete module which is free from any dependencies. It can be a good option if you are not looking for Angular Material like UI frameworks.

Subscribe
Notify of
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Hi,
I’m new using Angular and when I try follow this article I’m getting the following error:

Resource blocked due to MIME(text/html) type mismatch (X-Content-Type-Options: nosniff)