Angular 11 Autocomplete using Angular Material Example - Yudhy Network

Share on:

Yudhy Network - Angular 11 autocomplete example. In this tutorial, you will learn how to implement autocomplete search with ng material in the angular 11 app.

Angular 11 autocomplete using angular material example. In this tutorial, you will learn how to implement autocomplete search using angular material in the angular 11 app.

In this tutorial will guide you step by step on how to implement autocomplete search using external apis with angular material in angular 11 app.

Angular 11 Autocomplete with Angular Material Tutorial Example

  • Step 1 – Create New Angular App
  • Step 2 – Add Code on Module.ts File
  • Step 3 – Add Code on View File
  • Step 4 – Add Code On Component ts File
  • Step 5 – Create Services
  • Step 6 – 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
Recommended:- Angular 11 Reactive Forms Validation Tutorial Example

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

ng add @angular/material

Step 2 – Add Code on 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 { }
Recommended:- Angular 11 Image Upload With Preview Tutorial

Step 3 – Add Code on View File

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

<h1>Angular 11 material input autocomplete with API example - Tutsmake.Com</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 4 – 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
       }))
     )
   }  
}
Recommended:- Angular 11 CRUD Application Tutorial Example

Step 5 – 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 5 – Start Angular App

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

ng serve

php -S localhost:8001

Recommended Angular Posts

Recommended:- Angular 11 Radio Button Reactive Form Example
Recommended:- Angular 11 Select Dropdown Example Tutorial
Recommended:- Angular 11 Stripe Payment Checkout Gateway Example
Recommended:- Angular 11 Multiple File Upload Tutorial Example
Recommended:- Angular 11 Google Maps Integration Tutorial Example
Recommended:- Angular 11 DataTable Tutorial Example
Recommended:- Angular 11 Facebook Login Tutorial Example
Recommended:- Angular 11 Pie Chart Tutorial with ng2-charts Example
Recommended:- Angular 11 Full Page Scrolling Example
Recommended:- Angular 11 Datatable Print, Export to CSV, Excel Example
Recommended:- Angular 11 Line Chart using JS Chart Tutorial Example
Recommended:- Angular 11 Star Rating Example
Recommended:- Angular 11 Bar Chart using JS Chart Tutorial Example

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus