Navigation

Friday 20 January 2023

Angular: An autocomplete/fuzzy search in textbox

Fuzzy search is more powerful than exact searching when used for approximate string matching and investigation. Fuzzy search is very useful when researching unfamiliar words.


Step 1: Please copy and paste the following code to your HTML page as shown below app.component.html



<h1>{{title}}</h1>
<div class="col-md-3">
    <div class="form-group">
      <label for="empid" class="bmd-label-floating"> Search User</label>
      <input type="text" class="form-control" [(ngModel)]="txtUserName"
        (keyup)="searchUser(txtUserName)" >      
      <div class="autocomplete" *ngIf="flag">
        <div id="myInputautocomplete-list" class="autocomplete-items">
          <div *ngFor="let usr of searchTerms" (click)="onselectUser(usr.name)">
            {{usr.name}}
            <br />
          </div>
        </div>
      </div>
    </div>
  </div>


Step 2: After the HTML code here is the TS code of the same page  app.component.ts.


import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { FormBuilder } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Fuzzy Search Example';
  public UserLst: any[] = [];
  searchTerms: any[]=[];
  flag: boolean=false;
  txtUserName: string="";
  constructor(private _apiService: ApiService,
    private formBuilder: FormBuilder,
  ) { }

  ngOnInit() {
    this._apiService.getUser().subscribe(res =>{
      this.UserLst = res;
    });
  }
  searchUser(value: string): void {  
    debugger;
    this.flag = true;  
    this.searchTerms = this.UserLst.filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1)
  }  
  onselectUser(Obj:any):boolean{  
    debugger;  
    this.txtUserName = ""
    if (Obj.name != "") {  
      this.flag = false;
      this.txtUserName = Obj;  
      return true;
    }  
    else {  
      return false;  
    }  
  }
}


Step 3: For the proper view of the search following CSS is required. You can change it according to your requirements. app.component.css

.autocomplete {
    position: relative;
    display: inline-block;
    width:80%;
  }   
 
  .autocomplete-items {
    position: absolute;
    border: 1px solid #d4d4d4;
    border-bottom: none;
    border-top: none;
    z-index: 99;
    /*position the autocomplete items to be the same width as the container:*/
    top: 100%;
    left: 0;
    right: 0;
    max-height: 200px;
    overflow: auto;
  }
 
  .autocomplete-items div {
    padding: 10px;
    cursor: pointer;
    background-color: #fff;
    border-bottom: 1px solid #d4d4d4;    
  }
  .autocomplete-items a {
    text-decoration: none !important;
  }
  /*when hovering an item:*/
  .autocomplete-items div:hover {
    background-color: #81c7f0;
  }
 
  /*when navigating through the items using the arrow keys:*/
  .autocomplete-active {
    background-color: DodgerBlue !important;
    color: #ffffff;
  }


Step 4: To get the user list from API you have to add one service file like in this project I have used. api.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private BASE_API_URL = "https://gorest.co.in/public/";


  private _controllerName: string = "v2/";
  private _url: string = this.BASE_API_URL + this._controllerName;
  private _methodName: string = "";

  private _param:any={}; 
  private httpOptions = {
    _headers: new HttpHeaders({
      'Content-Type': 'applicantion/json'
    })
  };
  constructor(private _http: HttpClient) {

    console.log('Hello Service Provider');
  }
  getUser(): Observable<any[]> {
    this._methodName = "users/"
    return this._http.get<any[]>(this._url + this._methodName);
  }
}


 Step 5: app.module.ts file has the following component that is required for this project.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule      
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }




and in the last image, you can see the complete structure of the project.



You can also use this angular-ng-autocomplete





No comments:

Post a Comment