Home ยป Angular 12 autocomplete with API Data

Angular 12 autocomplete with API Data

Angular material autocomplete is a typeahead search component to search the items based on the user entered text on the text box, In this article, we are going to learn angular material auto-complete integrated with remote API. let’s start Angular 12 autocomplete with API.

You can download the working example https://github.com/technostuf/tinymce-angular-demo

  • Create a new Angular 12 app
  • Install @angular/material Library
  • Import the modules
  • Add code in the view file
  • Add code in the component file
  • Run an Angular 12 application

Create a new Angular 12 app

Open your terminal and execute the below command to create a new Angular 12 app. just copy the below command and paste in terminal

 ng new angular-material-auto-complete

Install @angular/material Library

To install the @angular/material Library in the Angular application using the below command

 ng add @angular/material

After running the above command, system will ask to select the theme and style method, select the Yes/No as per your choice

Import the modules

In this step, we will import the required modules into the app, now open the src\app\app.module.ts See the highlighted lines below

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

// Material Modules
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    MatInputModule,
    MatIconModule,
    MatButtonModule,
    MatAutocompleteModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add code in the view file

Open the src\app\app.component.html file and add the below code for material autocomplete input

  <div class="flexbox-parent center">
    <div layout="row" layout-align="center center" style="min-height: 500px">
      <h2>
        Angular material autocomplete search - technostuf.com
      </h2>
      <mat-form-field>
        <input matInput placeholder="Search Tags" [(ngModel)]="selectedTag" [matAutocomplete]="auto"
          [formControl]="searchTagCtrl" placeholder="Min 2 Characters">
        <button *ngIf="selectedTag" matSuffix mat-icon-button aria-label="Clear" (click)="clearTags()">
          <mat-icon>close</mat-icon>
        </button>
        <mat-autocomplete [panelWidth]="500" #auto="matAutocomplete" (optionSelected)="onSelected()"
          [displayWith]="displayWith">
          <mat-option *ngIf="isLoading" class="is-loading">Loading...</mat-option>
          <ng-container *ngIf="!isLoading">
            <mat-option *ngFor="let tag of filteredTags" [value]="tag">
              <span>{{tag.name}}</span>
            </mat-option>
          </ng-container>
        </mat-autocomplete>
      </mat-form-field>
      <br><br>
      <ng-container *ngIf="errorMsg; else elseTemplate">
        {{errorMsg}}
      </ng-container>
      <ng-template #elseTemplate>
        <div *ngIf="selectedTag?.name">
          <div>
            <h3>Selected Tag: {{selectedTag?.name}}</h3>
          </div>
        </div>
      </ng-template>
    </div>
  </div>

Add code in the component file

Open the app.component.ts file and update with the following code:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, tap, switchMap, finalize, distinctUntilChanged, filter } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-material-auto-complete';
  searchTagCtrl = new FormControl();
  filteredTags: any;
  isLoading = false;
  errorMsg!: string;
  minLengthTerm = 2;
  selectedTag: any = "";

  constructor(
    private http: HttpClient
  ) { }
  
  onSelected() {
    this.selectedTag = this.selectedTag;
  }

  displayWith(value: any) {
    return value?.Title;
  }

  clearTags() {
    this.selectedTag = "";
    this.filteredTags = [];
  }

  ngOnInit() {
    this.searchTagCtrl.valueChanges
      .pipe(
        filter(res => {
          return res !== null && res.length >= this.minLengthTerm
        }),
        distinctUntilChanged(),
        debounceTime(1000),
        tap(() => {
          this.errorMsg = "";
          this.filteredTags = [];
          this.isLoading = true;
        }),
        switchMap(value => this.http.get('http://localhost/api-demo/tags?query='+value)
          .pipe(
            finalize(() => {
              this.isLoading = false
            }),
          )
        )
      )
      .subscribe((data: any) => {
        if (data['results'].length == 0) {
          this.errorMsg = data['error'];
          this.filteredTags = [];
        } else {
          this.errorMsg = "";
          this.filteredTags = data['results'];
        }
        console.log(this.filteredTags);
      });
  }
}

Run an Angular 12 application

Execute the following command on the terminal run the angular app

  ng serve --open

Output

Angular 12 autocomplete with API Data

You can download the working example.

https://github.com/technostuf/angular-material-auto-complete

Related Post

Leave a Comment

Your email address will not be published.

10 − two =