Typeahead In Angular Application

In my last article we discuss on how to use sortable in angular application. In these tutorial i discuss on how to create typeahead in Angular application.
First we need to add below line in our app.module.ts file.


.................
import { TypeaheadModule } from 'ngx-bootstrap';
...................
@NgModule({
  .........
  imports: [
                TypeaheadModule.forRoot(),
            ...
           ]
})
export class AppModule(){}



After adding TypeaheadModule in the app module file. Now we can use these in any component.
Let’s create Basic code for the type-ahead elements.



<div class="card card-block">Output: {{selectedcontry | json}}</div>
<input [(ngModel)]="selectedcontry"
       [typeahead]="countries"
       class="form-control">


import { Component } from '@angular/core';

@Component({
selector: 'typeahead',
templateUrl: './typeahead.html'
})
export class TypeaheadComponent {
selectedcontry: string;
countries: string[] = [
'India',
'Albania',
'United Kingdom',
'United States',
'Vietnam',
'Canada',
'Brazil',
'Israel',
'South Africa',
'Australia'
];
}


Output of above display in below video.

You can easily implement type-ahead in form for auto suggest.


You can create template of displaying data form Type-ahead. display in below code.



<ng-template #typeaheadItemTemplate let-model="item" let-index="index">
  <h4> {{model | json}} Index of : {{ index }}</h4>
</ng-template>

<div class="card card-block">Output: {{selectedcontry | json}}</div>
<input [(ngModel)]="selectedcontry"
       [typeahead]="countries"
       [typeaheadItemTemplate]="typeaheadItemTemplate"
       class="form-control">


import { Component } from '@angular/core';
import 'rxjs/add/observable/of';

@Component({
selector: 'typeahead',
templateUrl: './typeahead.html'
})
export class TypeaheadComponent {
selectedcontry: string;
countries: string[] = [
'India',
'Albania',
'United Kingdom',
'United States',
'Vietnam',
'Canada',
'Brazil',
'Israel',
'South Africa',
'Australia'
];
}


Output display like in below video.

Spread the love
  • 24
  •  
  •  
  •  
  •  
  •  
  •  
  •