Angular 4 Autocomplete using ng2-completer Example:
Autocomplete is the important and most expected functionality in any end user application. Angular 2/4 has many ready-made components in github and npm repositories.
Below is the one good component which I came across for autocomplete functionality, this can be easily integrated and used with your angular apps.
Table of Contents
Step 1: Install ng2-completer component
npm install ng2-completer –save
Step 2: Import Ng2CompleterModule to your Module
Import Ng2CompleterModule to your module or app module.
import { Ng2CompleterModule } from “ng2-completer”;
Also import to your NgModule:
@NgModule({
imports:[RouterModule,FormsModule,Ng2CompleterModule],
declarations:[],
exports:[]
})
Note: Ensure the module also imports “FormsModule” else you will get NgModule is not recognized exception and page does not load.
Step 3: Import CompleterService, CompleterData,CompleterItem to your Component
import { CompleterService, CompleterData,CompleterItem } from ‘ng2-completer’;
Component code:
[html]
export class HeaderComponent{
protected searchStr: string;
protected captain: string;
protected selectedColor: string;
protected dataService: CompleterData;
protected searchData = [
{ color: ‘red’, value: ‘#f00’, },
{ color: ‘green’, value: ‘#0f0’ },
{ color: ‘blue’, value: ‘#00f’ },
{ color: ‘cyan’, value: ‘#0ff’ },
{ color: ‘magenta’, value: ‘#f0f’ },
{ color: ‘yellow’, value: ‘#ff0’ },
{ color: ‘black’, value: ‘#000’ },
{ color: ‘flipkart’, value: ‘flipkart-coupons’ }
];
constructor(private completerService: CompleterService, private router:Router) {
this.dataService = completerService.local(this.searchData, ‘color’, ‘color’);
}
protected onSelected(item: CompleterItem) {
this.selectedColor = item? item.title: “”;
this.router.navigate([‘/store/’+this.selectedColor]);
}
}
[/html]
Step 4: Add ng2-complete in your template code:
[html]
<ng2-completer input-class=”form-control form-control-small” [(ngModel)]=”searchStr” [datasource]=”dataService” [minSearchLength]=”0″ [autofocus]=”true”
[minSearchLength]=”0″ [clearSelected]=”true” (selected)=”onSelected($event)” [selectOnClick]=”true”></ng2-completer>
[/html]
Things to Note:
- Even though ng2-completer is good component, if your application is with angular and bootstrap you can go ahead with ngx-bootstrap typeahead to get the better UI.
- This above autocomplete example takes the data from local, but ng2-completer provides the autocomplete from remote data as well and lot of customization options are also available.
Have a look at the official documentations below to customize and make use in your projects,
Full documentation on ng2-completer can be found at,
ng2-completer in Github
ng2-completer in npm repository