How to Implement Autocomplete Search Using Angular Material in Angular

Angular Material is a UI component library that provides a set of reusable, well-tested, and accessible UI components. It is based on the Material Design specification, which is a set of design principles and guidelines for creating user interfaces that are both beautiful and functional.

Angular Material is a popular choice for building Angular apps because it provides a wide range of components that can be used to create a variety of UIs. These components are all built with Angular, so they are easy to use and integrate with other Angular components.

In this tutorial, we will learn how to implement autocomplete search using angular material in angular 14 apps. To implement autocomplete search using angular material in angular 14 apps we follow the following steps.

  • Step 1: Create New Angular App
  • Step 2: Install Material Package
  • Step 3: Import Modules in Module.ts File
  • Step 4: Create Autocomplete HTML on View File
  • Step 5: Add Code On Component ts File
  • Step 6: Create Services
  • Step 7: Start Angular App

Step 1: Create New Angular App

First of all, open your terminal and execute the following command on it to install angular app:

ng new my-new-app

Step 2: Install Material Package

Then execute the following command on terminal to install angular material:

ng add @angular/material

Step 3: Import Modules in Module.ts File

In this step, visit src/app directory and open app.module.ts file. Then add the following code into it:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
       
import { AppComponent } from './app.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
   
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
   
import {MatAutocompleteModule} from '@angular/material/autocomplete';
   
import { HttpClientModule } from '@angular/common/http';
   
@NgModule({
  declarations: [
    AppComponent
  ],
  imports:      [
    BrowserModule, 
    BrowserAnimationsModule,
    MatFormFieldModule,
    MatInputModule,
    MatAutocompleteModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Create Autocomplete Html on View File

In this step, create simple reactive form to get input values of autocomplete search. So, visit src/app/app.component.html and update the following code into it:

<h1>Angular 14 material input autocomplete with API example</h1>
   
<form class="example-form">
    <mat-form-field>
       <input
               type="text"
               placeholder="Enter Location"
               [formControl]="myControl"
               matInput
               [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option
                *ngFor="let option of filteredOptions | async"
                [value]="option.name">
              {{option.name}}
           </mat-option>
       </mat-autocomplete>
    </mat-form-field>
</form>

Step 5: Add Code On Component ts File

In this step, visit the src/app directory and open app.component.ts. Then add the following code into component.ts file:

import { Component } from '@angular/core';
import {Observable} from 'rxjs';
import { startWith, debounceTime, distinctUntilChanged, switchMap, map } from 'rxjs/operators';
import {FormControl} from '@angular/forms';
import { PostService } from './post.service';
   
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
   
export class AppComponent {
   
  myControl = new FormControl();
  options = [];
  filteredOptions: Observable;
 
   
  constructor(private service: PostService) {
     this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      debounceTime(400),
      distinctUntilChanged(),
      switchMap(val => {
            return this.filter(val || '')
       }) 
    )
   }
   
  filter(val: string): Observable {
 
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => { 
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }  
}

Step 6: Create Service

In this step, visit the src/app/ directory and open or create post.service.ts. Then add the following code into post.service.ts file:

import { Injectable } from '@angular/core';
 
import { HttpClient } from '@angular/common/http';
 
import { tap, map } from 'rxjs/operators';
 
import { of } from 'rxjs';
 
 
@Injectable({
 
  providedIn: 'root'
 
})
 
export class PostService {
 
 
  constructor(private http: HttpClient) { }
 
 
    opts = [];
 
 
    getData() {
 
 
          return this.opts.length ?
 
            of(this.opts) :
 
            this.http.get('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
 
 
    }
 
}

Step 7 – Start Angular App

In this step, execute the following commands on terminal to start angular app:

ng serve

Happy Coding !!!

#angular 

How to Implement Autocomplete Search Using Angular Material in Angular
1.45 GEEK