npm i angular-ng-autocomplete
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {AutocompleteLibModule} from 'angular-ng-autocomplete'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AutocompleteLibModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { keyword = 'name'; public countries = [ { id: 1, name: 'Albania', }, { id: 2, name: 'Belgium', }, { id: 3, name: 'Denmark', }, { id: 4, name: 'Montenegro', }, { id: 5, name: 'Turkey', }, { id: 6, name: 'Ukraine', }, { id: 7, name: 'Macedonia', }, { id: 8, name: 'Slovenia', }, { id: 9, name: 'Georgia', }, { id: 10, name: 'India', }, { id: 11, name: 'Russia', }, { id: 12, name: 'Switzerland', } ]; selectEvent(item) { // do something with selected item } onChangeSearch(search: string) { // fetch remote data from here // And reassign the 'data' which is binded to 'data' property. } onFocused(e) { // do something } } |
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<div class="ng-autocomplete"> <ng-autocomplete [data]="countries" [searchKeyword]="keyword" placeholder="Enter the Country Name" (selected)='selectEvent($event)' (inputChanged)='onChangeSearch($event)' (inputFocused)='onFocused($event)' historyIdentifier="countries" [itemTemplate]="itemTemplate" [notFoundTemplate]="notFoundTemplate"> </ng-autocomplete> <ng-template #itemTemplate let-item> <a [innerHTML]="item.name"></a> </ng-template> <ng-template #notFoundTemplate let-notFound> <div [innerHTML]="notFound"></div> </ng-template> </div> |
app.component.css
1 2 3 4 5 6 |
.ng-autocomplete { width:100%; max-width: 600px; display: table; margin: 0 auto; } |
FULL SOURCE CODE