Angular 8/9 Autocomplete Tutorial with Angular Material

By Digamber Rawat Last updated on
Today we are going to create Autocomplete in Angular 8/9 using Angular Material UI components. The autocomplete is a functionality which shows the recommended options to the user when the user clicks on the input field or enters some keywords in an input field. We’ll create an Angular 8 app from scratch to show how to create the autocomplete functionality.

In order to create autocomplete in Angular 9, we will set up a basic app using Angular, and then we’ll install and configure Angular material 8 UI framework. Then, we’ll import MatAutocompleteModule in the app.

This directive is used to build autocomplete in Angular 8/9. It helps user to show all the possible results, when the user types something in the input box. Then it shows the recommended options to the user in a dropdown.

Step 1: Install Angular App

Run command to install the Angular app, will show Angular 8/9 autocomplete here using Angular Material Autocomplete component.

ng new angular8-autocomplete-app

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? SCSS

Go inside the project folder.

cd angular8-autocomplete-app

Step 2: Install & Configure Angular Material

Enter the cmd to install Angular Material 8 library in autocomplete app:

ng add @angular/material

Choose Angular Material Pre-built Theme:

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink

❯ Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ] 
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ] 
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]
# Set up HammerJS for gesture recognition? (Y/n) = Y
# ? Set up browser animations for Angular Material? (Y/n) = Y

To know more about Angular Material, please visit the official angular material site here.

Step 3: Custom Angular Material Module File

Create a custom angular-material.module.ts file, In this custom angular-material module file we can import various ui components from Angular material ui library. However, we are going to import only MatAutocompleteModule and MatInputModule directives.

Go to app > angular-material.module.ts file and add the following code.

import { NgModule } from '@angular/core';
import {
    MatAutocompleteModule,
    MatInputModule
} from '@angular/material';

@NgModule({
    imports: [MatAutocompleteModule,MatInputModule],
    exports: [MatAutocompleteModule,MatInputModule]
})

export class AngularMaterialModule { }

Import Angular Material module file inside the app.module.ts file.

/* Angular material */
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [...],
  imports: [
    BrowserAnimationsModule,
    AngularMaterialModule,
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

export class AppModule { }

Step 4: Importing Reactive Forms & FormsModule in App Module

To make the input field and dropdown menu work properly, we will import FormsModule, ReactiveFormsModule from from ‘@angular/forms’.

app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [...],
  imports: [
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [...]
})

export class AppModule { }

Step 5: Create Autocomplete in Angular 8/9

In the below autocomplete example, we will create a simple autocomplete recommendation search bar.

<mat-form-field>
   <input type="text" placeholder="Enter Location" matInput [formControl]="myControl"
        [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of options" [value]="option">
          {{option}}
       </mat-option>
   </mat-autocomplete>
</mat-form-field>

Go to app.component.ts file and add the following code:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

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

export class AppComponent {
  myControl = new FormControl();
  options: string[] = ['Delhi', 'Mumbai', 'Banglore'];
}

As you can see we have used autocomplete directive to checkout the autocomplete demo on the browser: http://localhost:4200

$ ng serve

Angular Material 8 Autocomplete Examples

Checkout few autocomplete examples below:

Step 6: Create Option Groups in Autocomplete Dropdown

We can use mat-option directive to put the data into the groups using the mat-optgroup element:

app.component.html

<div class="container">
  <form [formGroup]="stateForm">
    <mat-form-field>
      <input type="text" matInput placeholder="States Group" formControlName="stateGroup" required [matAutocomplete]="autoGroup">
        <mat-autocomplete #autoGroup="matAutocomplete">
          <mat-optgroup *ngFor="let group of stateGroupOptions | async" [label]="group.letter">
            <mat-option *ngFor="let name of group.names" [value]="name">
              {{name}}
            </mat-option>
        </mat-optgroup>
      </mat-autocomplete>
    </mat-form-field>
  </form>
</div>

app.component.ts

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {Observable} from 'rxjs';
import {startWith, map} from 'rxjs/operators';

export interface StateGroup {
  letter: string;
  names: string[];
}

export const _filter = (opt: string[], value: string): string[] => {
  const filterValue = value.toLowerCase();

  return opt.filter(item => item.toLowerCase().indexOf(filterValue) === 0);
};

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

export class AppComponent implements OnInit {
  stateForm: FormGroup = this._formBuilder.group({
    stateGroup: '',
  });

  stateGroups: StateGroup[] = [{
    letter: 'A',
    names: ['Alabama', 'Alaska', 'Arizona', 'Arkansas']
  }, {
    letter: 'C',
    names: ['California', 'Colorado', 'Connecticut']
  }, {
    letter: 'D',
    names: ['Delaware']
  }, {
    letter: 'F',
    names: ['Florida']
  }, {
    letter: 'G',
    names: ['Georgia']
  }, {
    letter: 'H',
    names: ['Hawaii']
  }, {
    letter: 'I',
    names: ['Idaho', 'Illinois', 'Indiana', 'Iowa']
  }, {
    letter: 'K',
    names: ['Kansas', 'Kentucky']
  }, {
    letter: 'L',
    names: ['Louisiana']
  }, {
    letter: 'M',
    names: ['Maine', 'Maryland', 'Massachusetts', 'Michigan',
      'Minnesota', 'Mississippi', 'Missouri', 'Montana']
  }, {
    letter: 'N',
    names: ['Nebraska', 'Nevada', 'New Hampshire', 'New Jersey',
      'New Mexico', 'New York', 'North Carolina', 'North Dakota']
  }, {
    letter: 'O',
    names: ['Ohio', 'Oklahoma', 'Oregon']
  }, {
    letter: 'P',
    names: ['Pennsylvania']
  }, {
    letter: 'R',
    names: ['Rhode Island']
  }, {
    letter: 'S',
    names: ['South Carolina', 'South Dakota']
  }, {
    letter: 'T',
    names: ['Tennessee', 'Texas']
  }, {
    letter: 'U',
    names: ['Utah']
  }, {
    letter: 'V',
    names: ['Vermont', 'Virginia']
  }, {
    letter: 'W',
    names: ['Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
  }];

  stateGroupOptions: Observable<StateGroup[]>;

  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit() {
    this.stateGroupOptions = this.stateForm.get('stateGroup')!.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filterGroup(value))
      );
  }

  private _filterGroup(value: string): StateGroup[] {
    if (value) {
      return this.stateGroups
        .map(group => ({letter: group.letter, names: _filter(group.names, value)}))
        .filter(group => group.names.length > 0);
    }

    return this.stateGroups;
  }
}

Step 7: Highlight First Option in Angular 8/9 Autocomplete

In next example we are going to highlight the first option automatically in Autocomplete dropdown in Angular 8/9 option menu bar.

app.component.html

<mat-form-field>
  <input type="text" placeholder="Enter City" matInput [formControl]="myControl" [matAutocomplete]="auto">
  <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{option}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

app.component.ts

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

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

export class AppComponent implements OnInit {
  myControl = new FormControl();
  options: string[] = ['Delhi', 'Mumbai', 'Banglore'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
  }
}

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.