A simple Angular2 typeahead/autocomplete component with no third-party dependencies.
npm install ng2-typeahead-dumpennpm i ng2-typeahead --save
ng2-typeahead contains one directive: typeahead.
javascript
import { Typeahead } from 'ng2-typeahead';
@NgModule({
declarations: [ Typeahead ],
})
@Component({
selector: 'my-component',
template: require('./my.component.html')
})
export class MyComponent {
fruits: any[] = [
{
id: 1,
name: "1 - Apple",
searchText: "apple"
},
{
id: 2,
name: "2 - Orange",
searchText: "orange"
},
{
id: 3,
name: "3 - Banana",
searchText: "banana"
}
];
selectedFruit: any = this.fruits[0];
public fruitSelected(fruit) {
this.selectedFruit = fruit;
}
}
`
###### my.component.html
`html
[(ngModel)]="selectedFruit"
[list]="fruits"
[searchProperty]="'searchText'" [displayProperty]="'name'"
[maxSuggestions]="2"
(suggestionSelected)="fruitSelected($event)"
placeholder="Begin typing a fruit">
`
The following adjustments may be required in systemjs.config.js to run the example code.
Issue #7
`
var map = {
...
'ng2-typeahead': 'node_modules/ng2-typeahead',
};
...
var packages = {
...
'ng2-typeahead': { main: 'ng2-typeahead.js', defaultExtension: 'js' }
};
`
###### Demo

API for
typeahead
This is the only directive. Provide a list of suggestions as an object array, specify the display and search properties, and handle the selection event however you like.
$3
Binding Property | Type | Remarks
------------ | ---------- | -------------
[(ngModel)] | any | The model property to which the component is bound. Optional.
[list] | any[] | The complete list of items. These can be any type of object. This is required.
[displayProperty] | string | The property of a list item that should be displayed. The default is 'name'.
[searchProperty] | string | The property of a list item that should be used for matching. The default is 'name'.
[maxSuggestions] | number | The maximum number of suggestions to display. The default is -1 (no limit).
Note: displayProperty and searchProperty can be the same property or different properties based on your needs.
$3
Event Binding | Remarks
------------ | -------------
(suggestionSelected) | Called when a suggestion has been selected. The only parameter is the selected item.
$3
Selector | Remarks
------------ | -------------
.typeahead | The outer div which holds all component elements.
.typeahead-input | The input element into which the user enters text.
.typeahead-input-has-selection | The input element into which the user enters text when a suggestion is selected. This alerts the user that a selection has been made.
.typeahead-typeahead | The type-ahead input element which displays the suggested text.
.typeahead-suggestions | The div which holds the suggestions elements.
.typeahead-suggestions ul | The unordered list of suggestions.
.typeahead-suggestions ul li | The individual suggestion elements.
.typeahead-suggestion-active` | The active (highlighted) suggestion in the suggestions list.