Angular Material 13 Autocomplete Component Examples

Angular 12 autocomplete tutorial, In this tutorial, you will see how to create a reusable autocomplete component in the angular app using the angular material package.

Generically, this impeccable guide will step by step explain to you about creating a new project with angular cli, installing the material library in angular, importing autocomplete modules, form modules for making various autocomplete examples.

We will create the autocomplete user-interface module, it will be a standard text input and it will be amplified by a panel of suggested choices.

The references are displayed from a json object although you can get the predefined list of recommendations from the remote server using the REST API.

Angular Material 13 Autocomplete Examples

  • Step 1: Create Angular Project
  • Step 2: Install Angular Material Package
  • Step 3: Add Material Autocomplete Module
  • Step 4: Implement Simple Autocomplete in Angular
  • Step 5: Simple Input Autocomplete Example
  • Step 6: Option Group Autocomplete
  • Step 7: Run Development Server

Create Angular Project

For working with an angular app, you need to install angular cli on your system:

npm install @angular/cli -g

Now you are ready to start the angular project installation:

ng new my-demo-app

Get into the project root:

cd my-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Install Angular Material Package

Installing a material library is exorbitantly effortless, use the given below schematic:

ng add @angular/material

Here are the questions manifest on the console screen, answer them respectively based on your choice:

  1. Choose a prebuilt theme name or “custom” for a custom theme:

    You can choose from prebuilt material design themes or set up an extensible custom theme.

  2. Set up global Angular Material typography styles:

    Whether to apply the global typography styles to your application.

  3. Set up browser animations for Angular Material:

    Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.

Then, place the pre-built CSS in src/styles.scss file:

html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Add Material Autocomplete Module

Next, you need to open and update app.module.ts file with MatAutocompleteModule, MatFormFieldModule, MatInputModule, FormsModule and ReactiveFormsModule.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

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

import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatAutocompleteModule } from '@angular/material/autocomplete';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatFormFieldModule,    
    MatAutocompleteModule,
    FormsModule, 
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

This likely means that the library (@angular/material/toolbar) which declares MatToolbarModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library’s authors to see if the library is expected to be compatible with Ivy.

export declare class MatToolbarModule {
                       ~~~~~~~~~~~~~~~~
src/app/angular-material.module.ts:53:14 - error NG6002: Appears in the NgModule.imports of ComponentsModule, but itself has errors

If you get the above error, then insert the giving code in package.json file:

{
  "scripts": {
    "postinstall": "ngcc"
  }
}

Implement Simple Autocomplete in Angular

In the first example, you will ascertain how a material autocomplete is created. It is a combination of the form input field in which a list of suggestion is inoculated.

Here is the example where mat-form-field is the wrapper around mat-autocomplete directive.

Open and update below code in app.component.html file:

<mat-form-field style="width: 300px; margin: 50px auto; display: block;">

  <input type="text" placeholder="Netflix Webseries" matInput [formControl]="formControl" [matAutocomplete]="auto">

  <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
    <mat-option *ngFor="let item of autoFilter | async" [value]="item">
      {{item}}
    </mat-option>
  </mat-autocomplete>

</mat-form-field>

Open and update below code in app.component.ts file:

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

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

import {map, startWith} from 'rxjs/operators';
import {Observable} from 'rxjs';


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

export class AppComponent implements OnInit {
  
  formControl = new FormControl();
  autoFilter: Observable<string[]>;
  Items: string[] = ['BoJack Horseman', 'Stranger Things', 'Ozark', 'Big Mouth'];

  ngOnInit(): void { 
    this.autoFilter = this.formControl.valueChanges.pipe(
      startWith(''),
      map(value => this.mat_filter(value))
    );    
  }

  private mat_filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.Items.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
  }  
  
}

Implement Simple Autocomplete in Angular

Implement Input Autocomplete with Custom Filter

Here is the essential input autocomplete example with custom filter to align in autocomplete input.

In the first example, you will ascertain how a material autocomplete is created. It is a combination of the form input field in which a list of suggestion is inoculated.

Here is the example where mat-form-field is the wrapper around mat-autocomplete directive.

Open and update the following code in app.component.html
file:

<mat-form-field style="width: 300px; margin: 50px auto; display: block;">

  <input matInput type="text" placeholder="Search Netflix Webseries" [formControl]="formControl" [matAutocomplete]="auto">

  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let item of autoFilter | async" [value]="item">
      {{item}}
    </mat-option>
  </mat-autocomplete>

</mat-form-field>

Open and update the suggested code in app.component.ts file:

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

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

import {map, startWith} from 'rxjs/operators';
import {Observable} from 'rxjs';


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

export class AppComponent implements OnInit {
  
  formControl = new FormControl();
  autoFilter: Observable<string[]>;
  Items: string[] = ['BoJack Horseman', 'Stranger Things', 'Ozark', 'Big Mouth'];

  ngOnInit(): void { 
    this.autoFilter = this.formControl.valueChanges.pipe(
      startWith(''),
      map(value => this.mat_filter(value))
    );    
  }

  private mat_filter(value: string): string[] {
    const filterVal = this.mat_normalizeValue(value);
    return this.Items.filter(street => this.mat_normalizeValue(street).includes(filterVal));
  }

  private mat_normalizeValue(value: string): string {
    return value.toLowerCase().replace(/\s/g, '');
  }  
  
}

Material Autocomplete Option Group

Similarly, you can also add the suggestion group in suggestion drop down and filter out the related search into the autocomplete using the mat-option directive. It can be accumulated into groups with the help of the mat-optgroup element:

Open and update following code in app.component.ts file:

<mat-form-field style="width: 300px; margin: 50px auto; display: block;">

  <form [formGroup]="myForm">
    <mat-form-field>
      <input type="text" matInput placeholder="Names group" formControlName="namesGroup" required
        [matAutocomplete]="autoGroup">

      <mat-autocomplete #autoGroup="matAutocomplete">
        <mat-optgroup *ngFor="let itemGroup of dataGroupOptions | async" [label]="itemGroup.letter">
          <mat-option *ngFor="let item of itemGroup.names" [value]="item">
            {{item}}
          </mat-option>
        </mat-optgroup>
      </mat-autocomplete>
    </mat-form-field>
  </form>

</mat-form-field>

Add the provided code in app.component.ts file:

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

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


export interface NameGroup {
  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.scss']
})

export class AppComponent implements OnInit {

  myForm: FormGroup = this._formBuilder.group({
    namesGroup: '',
  });

  nameGroups: NameGroup[] = [{
    letter: 'A',
    names: ['Amelia', 'Alfie', 'Ava', 'Archie']
  }, 
  {
    letter: 'B',
    names: ['Brooke', 'Bethany', 'Beatrice']
  },
  {
    letter: 'C',
    names: ['Christopher', 'Caleb', 'Cameron', 'Charles']
  }, {
    letter: 'D',
    names: ['Daniel', 'Daisy']
  }, {
    letter: 'F',
    names: ['Freya', 'Florence', 'Francesca']
  }, {
    letter: 'G',
    names: ['Greyson', 'George']
  }, {
    letter: 'H',
    names: ['Harry', 'Harrison', 'Hannah']
  }, {
    letter: 'I',
    names: ['Idaho', 'Illinois', 'Indiana', 'Iowa']
  }
];

  dataGroupOptions: Observable<NameGroup[]>;

  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit() {
    this.dataGroupOptions = this.myForm.get('namesGroup')!.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filterGroup(value))
      );
  }

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

    return this.nameGroups;
  }
}

Run Development Server

Eventually, the time has come to test the autocomplete feature, hence run the command to start the angular development server:

ng serve

Here is the url which starts the app on the browser:

http://localhost:4200

Conclusion

The angular autocomplete tutorial is over, and we are sure you liked this post and share it with others.

In this article, we explored the best ways to implement the autocomplete in the angular app; additionally, we shared the innumerable autocomplete examples with you.

In this guide, we explained few examples. However, you can check out advanced examples here.