The Angular autocomplete is a normal input field, where we search for data by typing into the input field, which gives us suggestions and options based on what we type. There are many open-source libraries 3rd parties to implement autocomplete in Angular. In these articles, we’ll learn and demonstrate an example of autocomplete using ng-select and Angular material autocomplete.
The ng-select autocomplete library is one of my favorites, is a lightweight all-in-one UI Select, multi-select, and autocomplete. The autocomplete in angular improves user experience by supplying all possible lists of choices based on text user type in the input field. The ng-select is one of the most download and popular typeahead and also supports multi-select along with auto-complete. Some of the most popular autocomplete libraries for angular.
Library Name | Downloaded per Week | Size |
---|---|---|
ng-select | More or nearly 170,253 | 1.47 MB |
ngx-chips | More or nearly 36,576 | 1.69 MB |
ngx-mat-select-search | More or nearly 46,058 | 573 kB |
mat-autocomplete | Recommended with Angular material | Comes with Angular material |
Setting up and configure the project for Angular autocomplete.
Let’s first create our angular project and we’ll demonstrate Angular autocomplete using the ng-select library. Install the ng-select autocomplete library. We will create two examples of Angular autocomplete using ng-select.
- Single typeahead using custom typeahead provider for ionic autocomplete.
- Multiselect typeahead for ionic autocomplete search.
ng new angularAutoComplete
npm i @ng-select/ng-select --save
Styling ng-select theme for Angular Autocomplete.
To have a good UI for angular autocomplete we need to include, one of the ng-select themes in our project, The ng-select comes with its own theme, which are generic styles that are necessary for correct layout and positioning. To get the full look at the control, we have to import one of its themes in our style import in our styles.scss file in our project as.
@import “~@ng-select/ng-select/themes/material.theme.css”;
Import the NgSelect Module and angular FormsModule module in our Angular autocomplete project.
As we are using ng-select autocomplete on the input field of our form. To use the ng-select autocomplete library, we need to import forms and ng-select modules. Let import the above module in the app.module.ts file. We also, need to import HttpClientModule to retrieve our data from static JSON or server.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgSelectModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create Dummy data for Angular autocomplete.
We will create dummy data states.json containing a few US state names, create folder data, and create a new file states.json. Add the following few state names in assets/data/states.JSON as.
{
"states": [
{ "name": "Alabama" },
{ "name": "Alaska" },
{ "name": "Arizona" },
{ "name": "Arkansas" },
{ "name": "California" },
{ "name": "Colorado" },
{ "name": "Connecticut" },
{ "name": "Delaware" },
{ "name": "Florida" },
{ "name": "Georgia" },
{ "name": "Hawaii" },
{ "name": "Idaho" }
]
}
Example of Angular autocompletes using ng-select.
We have already configured the required task for Angular autocomplete. Let’s create a typeahead service. If you are using live API data for typehead, then it is the same process as using we are using in the typeahead service. We are using static JSON data using HTTP to get methods. Let’s create a typeahead service for angular ng-select.
We’ll demonstrate here’s a quick screenshot of what we’ll be building.
ng g service services/typeahead
Angular autocomplete service
In a real application, we might use angular autocomplete at any part of the application. We need to have a service for angular autocomplete and in our example, we have used autocomplete of one data source. In the typeahead.service.ts file edit the service to retrieve, and filter the Angular autocomplete task.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class TypeaheadService {
constructor(private http: HttpClient) { }
getStates(term: string = null): Observable<string[]> {
return new Observable((observer) => {
let getStatesNamePromise: Promise<any>;
getStatesNamePromise = new Promise((resolve) => {
this.http.get<string[]>('./assets/data/states.json').subscribe((data: any) => {
resolve(data.states);
});
});
getStatesNamePromise.then((data) => {
if (term) {
data = data.filter(x => x.name.toLocaleLowerCase().indexOf(term.toLocaleLowerCase()) > -1);
}
observer.next(data);
});
});
}
getRegions(term: string = null): Observable<string[]> {
return new Observable((observer) => {
this.http.get('./assets/data/states.json').subscribe((data: any) => {
observer.next(data.states);
});
});
}
}
Implement Angular autocomplete and multi-select in our component
In the app.component.ts we have to inject our typeahead service in the constructor and add the following code to get typeahead or angular autocomplete drop and multi-select in the app.component.ts file.
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { TypeaheadService } from './services/typeahead.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
form: FormGroup;
states: Observable<string[]>;
selectedCityNames;
cities2 = [
{ id: 1, name: 'New Delhi' },
{ id: 2, name: 'Mumbai' },
{ id: 3, name: 'New York', disabled: true },
{ id: 4, name: 'Paris' },
{ id: 5, name: 'London' }
];
constructor(private http: HttpClient, private typeahead: TypeaheadService) { }
getStatesName(event): void {
this.states = this.typeahead.getStates(event.target.value);
}
}
In the template, we need to subscribe to our observable using async as our data are async in nature in the real application. Edit app.component.html file.
<div class="form-group">
<form [formGroup]="form">
<div class="ng-select">
<h2 style="color: blue;">Auto complete using ng-select</h2>
<label>Select State</label>
<ng-select [items]="states | async" bindLabel="name" formControlName="name" notFoundText="No records found"
(keyup)="getStatesName($event)">
</ng-select>
</div>
</form>
<div class="multiSelect">
<h2 style="color: blue;">Multiple select using ng-select</h2>
<label style="color: red;">Multiselect with custom bindings</label>
<ng-select [items]="cities2" bindLabel="name" bindValue="name" [multiple]="true" placeholder="Select cities"
[(ngModel)]="selectedCityNames">
</ng-select>
<p style="color:greenyellow;">
Selected cities: {{ selectedCityNames }}
</p>
</div>
</div>
<router-outlet></router-outlet>
Example of Angular material autocomplete
The ng-select is one way to include Angular autocomplete, but if your project has Angular material added for UI. Then it is recommended to use Angular material autocomplete.
We’ll demonstrate here’s a quick screenshot of what we’ll be building.
Setup and configure Angular material autocomplete.
We’ll use some dummy data for Angular material autocomplete. We’ll continue the same project and need to add angular material. Angular material has the mat-autocomplete directive to achieve angular autocomplete in the Angular material project.
ng add @angular/material
Running the above command will ask to include angular material theme, typography, and font. Select and press yes to include typography and font in our project. Import Angular material autocomplete module, Angular material input, and form field in our project and let’s edit the app.module.ts file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgSelectModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
BrowserAnimationsModule,
MatAutocompleteModule,
MatFormFieldModule,
MatInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Implement Angular material autocomplete in our component
In the app.component.ts we implement angular material autocomplete. Edit app.component.ts typescript and template file.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { TypeaheadService } from './services/typeahead.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
form: FormGroup;
stateCtrl: FormControl;
filterRegions: Observable<any[]>;
data: string[] = [];
myControl = new FormControl();
constructor(private formBuilder: FormBuilder, private http: HttpClient, private typeahead: TypeaheadService) {
this.stateCtrl = new FormControl();
this.createForm();
}
ngOnInit(): void {
this.http.get('./assets/data/states.json').subscribe((res: any) => {
this.data = res.states;
});
this.filterRegions = this.stateCtrl.valueChanges.pipe(
startWith(''),
map(region => region ? this.getRegions(region) : this.data.slice())
);
}
createForm(): void {
this.form = this.formBuilder.group({
name: [],
});
}
getRegions(name: string): any {
return this.data.filter((x: any) => x.name.toLocaleLowerCase().indexOf(name.toLocaleLowerCase()) > -1);
}
}
<div class="form-group">
<form [formGroup]="form">
<div class="material-autocomplete">
<h2 style="color: blue;">Auto-complete using angular mateiral</h2>
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
[matAutocomplete]="auto" [formControl]="stateCtrl">
<mat-autocomplete #auto="matAutocomplete" (keyup)="getRegions($event)">
<mat-option *ngFor="let option of filterRegions | async" [value]="option.name">
{{ option.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</form>
</div>
Conclusion:
We have completed our angular autocomplete using ng-select and angular material autocomplete. We also demonstrate angular autocomplete multi-select also. To check the complete code of angular autocompletes on the GitHub repository.
Related posts
- How to add an Angular signature pad?
- How to install Angular material
- How to implement CKEditor in Angular
- How to use to implement HighCharts Angul