Here I am going to implement an auto complete feature using HTML 5 tag datalist along with using Angular. Advantage of using this tag is that no need to write any logic into your ts(js) file. In my previous article I have explained about creating an autocomplete using angular 2/5 from scratch. Let us check the same using html5.
AutoComplete using HTML5 + Angular
Html
<div class="typeHead">
<input type="text" list="countries" name="country" [(ngModel)]='selected' (change)="selectCountryName(selected)" />
<datalist id="countries">
<select>
<option *ngFor="let c of countrylist" [value]="c.name"></option>
</select>
</datalist>
</div>
Angular role is very less here, autocomplete feature is taken care by html 5 datalist. Angular is used here only to set and get the selected values. Check below component code as well.
Component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'auto-complete',
templateUrl: '../autoComplete/autoComplete.html',
})
export class autoCompleteComponent {
countrylist: any[];
selected: string = "";
ngOnInit() {
this.countrylist = [
{ "name": "Afghanistan", "code": "AF" },
{ "name": "Ă…land Islands", "code": "AX" },
{ "name": "Albania", "code": "AL" },
{ "name": "Algeria", "code": "DZ" },
{ "name": "American Samoa", "code": "AS" },
{ "name": "AndorrA", "code": "AD" },
{ "name": "Angola", "code": "AO" },
{ "name": "Anguilla", "code": "AI" },
{ "name": "Antarctica", "code": "AQ" },
{ "name": "Antigua and Barbuda", "code": "AG" },
{ "name": "Argentina", "code": "AR" },
{ "name": "Armenia", "code": "AM" },
{ "name": "Aruba", "code": "AW" },
{ "name": "Australia", "code": "AU" },
{ "name": "Austria", "code": "AT" },
{ "name": "Azerbaijan", "code": "AZ" },
{ "name": "Bahamas", "code": "BS" },
{ "name": "Bahrain", "code": "BH" },
{ "name": "Bangladesh", "code": "BD" },
{ "name": "Barbados", "code": "BB" }
]
}
selectCountryName(name) {
console.log(name);
console.log(this.selected);
}
}
selectCountryName is the method where we are getting the selected country list. You can console the output as console.log (name) or console.log (this.selected). In the above example you may notice that I have added a <select></select>
tag in-between datalist. This will help you to show a select box if any old browser doesn't support HTML 5 datalist. If you are facing any compatibility issues on any older Brower, you can include datalist - polyfill as well.
If you don't want to use this solution you can check this link : - Autocomplete using angular from scratch.
In this article we have discussed about creating an autocomplete feature using HTML 5 + Angular.
Related Info
1. Http calls in Angular with simple examples.
2. 5 different ways for conditionally adding class - Angular.
3. Angular 2/4 routing with simple examples.
4. Login authentication flow using angular auth guard - Angular 5
No comments :
Post a Comment