Angular Bootstrap autocomplete

Angular Autocomplete - Bootstrap 4 & Material Design

Angular Bootstrap autocomplete is a component which predicts the words basing on the first few letters given by a user, while one is typing it.

Warning notification

In the MDB Angular 7.2.0 version, the mdb-autocomplete component was changed to mdb-auto-completer. Its construction is completely different. The following documentation presents a new version of this component. If you are still using the old version, its documentation can be found here. In MDB Angular 8 we will remove the old version of mdb-autocomplete, so we recommend that you migrate to the new version as soon as possible.


Basic example MDB Pro component


        <div class="md-form">
          <input type="text" class="completer-input form-control mdb-autocomplete"
                 [(ngModel)]="searchText"
                 (input)="getFilteredData()" (ngModelChange)="onChange()"
                 [mdbAutoCompleter]="auto"
                 placeholder="Choose your color">
          <mdb-auto-completer #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
            <mdb-option *ngFor="let option of results | async" [value]="option">
              {{option}}
            </mdb-option>
          </mdb-auto-completer>
        </div>
      

        import {AfterViewInit, Component, ViewChild} from '@angular/core';
        import {of} from 'rxjs';
        import {MdbAutoCompleterComponent} from 'ng-uikit-pro-standard';

        @Component({
          selector: 'basic-auto-completer',
          templateUrl: './basic-auto-completer.component.html',
          styleUrls: ['./basic-auto-completer.component.scss'],
        })
        export class BasicAutoCompleterComponent implements AfterViewInit {
        @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;
        searchText = '';
        results: any;
        data: any = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

        constructor() {
          this.results = this.searchEntries(this.searchText);
        }

        getDataItems() {
          return this.data;
        }

        searchEntries(term: string) {
          return of(this.getDataItems().filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
        }

        getFilteredData() {
          this.results = this.searchEntries(this.searchText);
        }

        onChange() {
          this.getFilteredData();
        }

        ngAfterViewInit() {
          this.completer.selectedItemChanged().subscribe((data: any) => {
            this.searchText = data.text;
            this.getFilteredData();
          });
         }
        }

      

Disabled autocomplete MDB Pro component

Use disabled attribute on input element, and [disabled]="true" on the mdb-auto-completer element to disable the whole autocompleter component.


        <div class="md-form">
          <input type="text" disabled class="completer-input form-control mdb-autocomplete"
                 [(ngModel)]="searchText"
                 (input)="getFilteredData()" (ngModelChange)="onChange()"
                 [mdbAutoCompleter]="auto"
                 placeholder="Choose your color">
          <mdb-auto-completer [disabled]="true" #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
            <mdb-option *ngFor="let option of results | async" [value]="option">
              {{option}}
            </mdb-option>
          </mdb-auto-completer>
        </div>
      

        import {AfterViewInit, Component, ViewChild} from '@angular/core';
        import {of} from 'rxjs';
        import {MdbAutoCompleterComponent} from 'ng-uikit-pro-standard';

        @Component({
        selector: 'disabled-completer',
        templateUrl: './disabled-completer.component.html',
        styleUrls: ['./disabled-completer.component.scss'],
        })
        export class DisabledCompleterComponent implements AfterViewInit {
        @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;
        searchText = '';
        results: any;
        data: any = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

        constructor() {
          this.results = this.searchEntries(this.searchText);
        }

        getDataItems() {
          return this.data;
        }

        searchEntries(term: string) {
          return of(this.getDataItems().filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
        }

        getFilteredData() {
          this.results = this.searchEntries(this.searchText);
        }

        onChange() {
          this.getFilteredData();
        }

        ngAfterViewInit() {
          this.completer.selectedItemChanged().subscribe((data: any) => {
            this.searchText = data.text;
            this.getFilteredData();
          });
         }
        }

      

Remote data MDB Pro component


        <div class="md-form">
          <input type="text" class="completer-input form-control mdb-autocomplete mb-0"
                 [(ngModel)]="searchText"
                 (input)="getFilteredData()" (ngModelChange)="onChange()"
                 [mdbAutoCompleter]="auto"
                 placeholder="Pick the Star Wars character">
          <mdb-auto-completer #auto="mdbAutoCompleter"  textNoResults="I have found no results :(">
            <mdb-option *ngFor="let option of results | async" [value]="option.name">
              <div class="d-flex flex-column">
                <strong>Name: {{option.name}}</strong>
                <small>Gender: {{option.gender}}</small>
                <small>Hair color: {{option.hair_color}}</small>
              </div>
            </mdb-option>
          </mdb-auto-completer>
        </div>
      

        import {Component} from '@angular/core';
        import {of} from 'rxjs';
        import {HttpClient} from '@angular/common/http';

        @Component({
          selector: 'remote-auto-completer',
          templateUrl: './remote-auto-completer.component.html',
          styleUrls: ['./remote-auto-completer.component.scss'],
        })
        export class RemoteAutoCompleterComponent {
        searchText = '';
        url = 'https://swapi.co/api/people/?search=';
        results: any;
        data: any;
        constructor(private httpClient: HttpClient) {
          this.httpClient.get(this.url + this.searchText).subscribe((data: any) => {
            console.log(data);
            this.data = data;
          });
        }

        getDataItems() {
          return this.data['results'];
        }

        searchEntries(term: string) {
          return of(this.getDataItems().filter((data: any) => data['name'].toString().toLowerCase().includes(term.toString().toLowerCase())));
        }

        getFilteredData() {
          this.results = this.searchEntries(this.searchText);
        }

        onChange() {
          if (this.searchText) {
            this.getFilteredData();
            }
          }
        }

      

Reactive forms MDB Pro component

In this section you will find informations on how to use our autocomplete component in reactive forms.

Remember to import ReactiveFormsModule in your's app.module.ts

Default value

Set default value in FormControl


        <form [formGroup]="testForm">
          <div class="md-form">
            <input formControlName="testAutocomplete" type="text" class="completer-input form-control mdb-autocomplete mb-0" (keydown)="searchText = $event.target.value"
                   (input)="getFilteredData()" (ngModelChange)="onChange()"
                   [mdbAutoCompleter]="auto"
                   placeholder="Choose your color">
            <mdb-auto-completer #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
              <mdb-option *ngFor="let option of results | async" [value]="option">
                {{option}}
              </mdb-option>
            </mdb-auto-completer>
          </div>
        </form>
      

        import {AfterViewInit, Component, ViewChild} from '@angular/core';
        import {of} from 'rxjs';
        import {MdbAutoCompleterComponent} from 'ng-uikit-pro-standard';
        import {FormControl, FormGroup} from '@angular/forms';

        @Component({
          selector: 'reactive-form-auto-completer',
          templateUrl: './reactive-form-auto-completer.component.html',
          styleUrls: ['./reactive-form-auto-completer.component.scss'],
        })
        export class ReactiveFormAutoCompleterComponent implements AfterViewInit {
        @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;
        searchText = '';
        results: any;
        data: any = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

        testForm: FormGroup;

        constructor() {
          this.results = this.searchEntries(this.searchText);
          this.testForm = new FormGroup({
            testAutocomplete: new FormControl()
          });
        }

        getDataItems() {
          return this.data;
        }

        searchEntries(term: string) {
          return of(this.getDataItems().filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
        }

        getFilteredData() {
          this.results = this.searchEntries(this.searchText);
        }

        onChange() {
          this.getFilteredData();
        }

        ngAfterViewInit() {
          this.completer.selectedItemChanged().subscribe((data: any) => {
            this.searchText = data.text;
            this.getFilteredData();
          });

        setTimeout(() => {
            this.testForm.controls['testAutocomplete'].setValue('red');
          }, 0);
         }

        }

      

Append to body MDB Pro component

In this section you will find informations on how to append mdb-auto-completer component to the body element.


        <div class="row">
          <div class="col-md-6 mx-auto my-5" style="overflow-y: hidden">
            <div class="md-form">
              <input type="text" class="completer-input form-control mdb-autocomplete"
                     [(ngModel)]="searchText"
                     (input)="getFilteredData()" (ngModelChange)="onChange()"
                     [mdbAutoCompleter]="auto"
                     placeholder="Choose your color">
              <mdb-auto-completer [appendToBody]="true" #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
                <mdb-option *ngFor="let option of results | async" [value]="option">
                  {{option}}
                </mdb-option>
              </mdb-auto-completer>
            </div>
          </div>
        </div>

      

        import { Component, ViewChild, AfterViewInit } from '@angular/core';
        import {MdbAutoCompleterComponent} from "../../projects/ng-uikit-pro-standard/src/lib/pro/auto-completer";
        import { of } from 'rxjs';

        @Component({
          selector: 'body-auto-completer',
          templateUrl: './body-auto-completer.component.html',
          styleUrls: ['./body-auto-completer.component.scss']
        })
        export class BodyAutoCompleterComponent implements AfterViewInit {
          @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;
          searchText = '';
          results: any;
          data: any = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

          constructor() {
            this.results = this.searchEntries(this.searchText);
          }

          getDataItems() {
            return this.data;
          }

          searchEntries(term: string) {
            return of(this.getDataItems().filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
          }

          getFilteredData() {
            this.results = this.searchEntries(this.searchText);
          }

          onChange() {
            this.getFilteredData();
          }

          ngAfterViewInit() {
            this.completer.selectedItemChanged().subscribe((data: any) => {
              this.searchText = data.text;
              this.getFilteredData();
            });
          }
        }
      

Angular Autocomplete - API

In this section you will find informations about required modules and available inputs, outputs, methods and events of autocomplete component.


Modules used

In order to speed up your application, you can choose to import only the modules you actually need, instead of importing the entire MDB Angular library. Remember that importing the entire library, and immediately afterwards a specific module, is bad practice, and can cause application errors.

API Reference for MDB Angular Autocomplete:
// MDB Angular Pro
import { AutoCompleterModule, InputsModule } from 'ng-uikit-pro-standard'
// MDB Angular Pro
import { FormsModule } from '@angular/forms'

Components

MdbAutoCompleterComponent

Selector: mdb-auto-completer

Type: MdbAutoCompleterComponent

MdbOptionComponent

Selector: mdb-option

Type: MdbOptionComponent


Directives

MdbAutoCompleterDirective

Selector: mdbAutoCompleter

Type: MdbAutoCompleterDirective

Export as: mdbAutoCompleterTrigger


Inputs

MdbAutoCompleterComponent
Name Type Default Description Example
textNoResults string - Changes no results text textNoResults="Custom text"
clearButton boolean true Shows the clear button clearButton="true"
clearButtonTabIndex number 0 Set the clear button tab index clearButtonTabIndex="1"
disabled boolean false Disable the mdb-auto-completer component [disabled]="true"
appendToBody boolean false If true, will append the mdb-auto-completer dropdown element to the body element. Helpful when mdb-auto-completer parent has a overflow: hidden [appendToBody]="true"
MdbOptionComponent
Name Type Default Description Example
value string - Option component value [value]="value"
MdbAutoCompleterDirective
Name Type Default Description Example
mdbAutoCompleter MdbAutoCompleterComponent - Auto Completer component binding [mdbAutoCompleter]="autocomplete"

Outputs

MdbAutoCompleterComponent
Name Type Description Example
select EventEmitter<any> Event emitted when item is selected (highlighted) (select)="onItemSelect($event)"
MdbAutoCompleterDirective
Name Type Description Example
clearBtnClicked EventEmitter<any> Event emitted when clear button is clicked (clearBtnClicked)="onClearButtonClick()"

Angular Autocomplete - examples & customization


Autocomplete with icons MDB Pro component


        <div class="md-form">
          <input type="text" class="completer-input form-control mdb-autocomplete mb-0"
                 [(ngModel)]="searchText"
                 (input)="getFilteredData()" (ngModelChange)="onChange()"
                 [mdbAutoCompleter]="auto"
                 placeholder="Pick person">
          <mdb-auto-completer #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
            <mdb-option *ngFor="let option of results | async" [value]="option.name">
              <div class="d-flex justify-content-between align-items-center w-100">
                <span>{{option.name}}</span>
                <img [src]="option.icon" alt="{{option.name}} photo" class="completer-image">
              </div>
            </mdb-option>
          </mdb-auto-completer>
        </div>
      

        import {AfterViewInit, Component, ViewChild} from '@angular/core';
        import {of} from 'rxjs';
        import {MdbAutoCompleterComponent} from 'ng-uikit-pro-standard';

        @Component({
          selector: 'auto-completer-with-icons',
          templateUrl: './auto-completer-with-icon.component.html',
          styleUrls: ['./auto-completer-with-icon.component.scss'],
        })
        export class AutoCompleterWithIconsComponent implements AfterViewInit {
          @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;
          searchText = '';
          results: any;
          data: any = [
            { name: 'Anthony', icon: 'https://mdbootstrap.com/img/Photos/Avatars/avatar-1.jpg' },
            { name: 'Jane', icon: 'https://mdbootstrap.com/img/Photos/Avatars/avatar-2.jpg' },
            { name: 'John', icon: 'https://mdbootstrap.com/img/Photos/Avatars/avatar-8.jpg' },
            { name: 'Samantha', icon: 'https://mdbootstrap.com/img/Photos/Avatars/avatar-4.jpg' }
          ];

          constructor() {
            this.results = this.searchEntries(this.searchText);
          }

          getDataItems() {
            return this.data;
          }

          searchEntries(term: string) {
            return of(this.getDataItems().filter((data: any) => data['name'].toString().toLowerCase().includes(term.toString().toLowerCase())));
          }

          getFilteredData() {
            this.results = this.searchEntries(this.searchText);
          }

          onChange() {
            this.getFilteredData();
          }

          ngAfterViewInit() {
            this.completer.selectedItemChanged().subscribe((data: any) => {
              this.searchText = data.text;
              this.getFilteredData();
            });
          }
        }

      

Second dependent on the first MDB Pro component

The selection of values in the first auto-completer determines the options to choose in the second auto-completer.


        <div class="row">
          <div class="col-md-4 mx-auto my-5">
            <div class="md-form">
              <input type="text" class="completer-input form-control mdb-autocomplete mb-0" [(ngModel)]="searchText"
                     (input)="getFilteredData()" (ngModelChange)="onChange()" placeholder="Choose your framework"
                     [mdbAutoCompleter]="auto">
              <mdb-auto-completer #auto="mdbAutoCompleter" textNoResults="I have found no results :(">
                <mdb-option *ngFor="let option of results | async" [value]="option">
                  {{option}}
                </mdb-option>
              </mdb-auto-completer>
            </div>
          </div>

          <div class="col-md-4 mx-auto my-5">
            <div class="md-form">
              <input type="text" class="completer-input form-control mdb-autocomplete mb-0" [(ngModel)]="searchText2"
                     (input)="getFilteredData2()" (ngModelChange)="onChange2()" placeholder="Choose your framework version"
                     [mdbAutoCompleter]="auto2">
              <mdb-auto-completer #auto2="mdbAutoCompleter" textNoResults="I have found no results :(">
                <mdb-option *ngFor="let option of results2 | async" [value]="option">
                  {{option}}
                </mdb-option>
              </mdb-auto-completer>
            </div>
          </div>
        </div>
      

        import {AfterViewInit, Component, ViewChild} from '@angular/core';
        import {of} from 'rxjs';
        import {MdbAutoCompleterComponent} from 'ng-uikit-pro-standard';

        @Component({
          selector: 'multiple-autocompleter',
          templateUrl: './multiple-autocompleter.component.html',
          styleUrls: ['./multiple-autocompleter.component.scss'],
        })
        export class MultipleAutoCompleterComponent implements AfterViewInit {
          @ViewChild(MdbAutoCompleterComponent) completer: MdbAutoCompleterComponent;

          searchText = '';
          searchText2 = '';

          results: any = null;
          results2: any = null;

          data: Array<any> = ['Angular', 'React', 'Vue', 'jQuery'];
          data2: Array<any> = [];

            constructor() {
              this.results = this.searchEntries(this.searchText);
              this.results2 = this.searchEntries2(this.searchText2);
            }

            getDataItems() {
              return {first: this.data, second: this.data2};
            }

            searchEntries(term: string) {
              return of(this.getDataItems().first.filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
            }

            searchEntries2(term: string) {
              return of(this.getDataItems().second.filter((data: any) => data.toString().toLowerCase().includes(term.toString().toLowerCase())));
            }

            getFilteredData() {
              this.results = this.searchEntries(this.searchText);
            }

            getFilteredData2() {
              this.results2 = this.searchEntries2(this.searchText2);
            }

            onChange() {
              this.getFilteredData();
            }

            onChange2() {
              this.getFilteredData();
            }

            ngAfterViewInit() {
              this.completer.selectedItemChanged().subscribe((data: any) => {
                this.searchText = data.text;
                this.getFilteredData();

                if (this.searchText === 'Angular') {
                this.data2 = ['Angular 1', 'Angular 2', 'Angular 3', 'Angular 4'];
                } else if (this.searchText === 'React') {
                this.data2 = ['React 1', 'React 2', 'React 3', 'React 4'];
                } else if (this.searchText === 'Vue') {
                this.data2 = ['Vue 1', 'Vue 2', 'Vue 3', 'Vue 4'];
                } else if (this.searchText === 'jQuery') {
                this.data2 = ['jQuery 1', 'jQuery 2', 'jQuery 3', 'jQuery 4'];
                }
                this.getFilteredData2();
              });
            }
          }

      

Remote call after input event MDB Pro component

The selection of values in the first auto-completer determines the options to choose in the second auto-completer.


        <div class="md-form">
          <input #inputEl type="text" class="completer-input form-control mdb-autocomplete mb-0"
                 [(ngModel)]="searchText"
                 [mdbAutoCompleter]="auto"
                 placeholder="Pick the Star Wars character">
          <mdb-auto-completer #auto="mdbAutoCompleter"  textNoResults="I have found no results :(">
            <mdb-option *ngFor="let option of results" [value]="option.name">
              <div class="d-flex flex-column">
                <strong>Name: {{option.name}}</strong>
                <small>Gender: {{option.gender}}</small>
                <small>Hair color: {{option.hair_color}}</small>
              </div>
            </mdb-option>
          </mdb-auto-completer>
        </div>
      

        import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
        import {fromEvent} from "rxjs";
        import {HttpClient} from "@angular/common/http";
        import {debounceTime} from "rxjs/operators";

        @Component({
          selector: 'remote-event',
          templateUrl: './remote-event.component.html',
          styleUrls: ['./remote-event.component.scss']
        })
        export class RemoteEventComponent implements AfterViewInit {
          @ViewChild('inputEl') inputEl: ElementRef;
          searchText = '';
          url = 'https://swapi.co/api/people/?search=';
          results: any = [];

          constructor(private httpClient: HttpClient) {  }

          ngAfterViewInit(): void {
            fromEvent(this.inputEl.nativeElement, 'input').pipe(debounceTime(250)).subscribe(() => {
              this.httpClient.get(this.url + this.searchText).subscribe((items: any) => {
                this.results = items['results'];
              });
            });
          }
        }