Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JoseRFJuniorLLMs/4b552811bc166476863ef919bc1589cd to your computer and use it in GitHub Desktop.
Save JoseRFJuniorLLMs/4b552811bc166476863ef919bc1589cd to your computer and use it in GitHub Desktop.
// taken from Tutorial: Creating an Angular2 Autocomplete by Leonardo Jines
// http://4dev.tech/2016/03/tutorial-creating-an-angular2-autocomplete/#comment-1609
import {Component, ElementRef} from 'angular2/core';
@Component({
selector: 'my-app',
host: {
'(document:click)': 'handleClick($event)',
},
template: `
<div class="container" >
<div class="input-field col s12">
<!--NEW: added $event to filter() and (keydown)=handleBlur() -->
<input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter($event) (keydown)=handleBlur() >
<label for="country">Country</label>
</div>
<div class="suggestions" *ngIf="filteredList.length > 0">
<ul *ngFor="#item of filteredList" >
<li >
<a (click)="select(item)">{{item}}</a>
</li>
</ul>
</div>
</div>
`
})
export class AppComponent {
public query = '';
public countries = [ "Albania","Andorra","Armenia","Austria","Azerbaijan","Belarus","Belgium","Bosnia & Herzegovina",
"Bulgaria","Croatia","Cyprus","Czech Republic","Denmark","Estonia","Finland","France","Georgia",
"Germany","Greece","Hungary","Iceland","Ireland","Italy","Kosovo","Latvia","Liechtenstein",
"Lithuania","Luxembourg","Macedonia","Malta","Moldova","Monaco","Montenegro","Netherlands",
"Norway","Poland","Portugal","Romania","Russia","San Marino","Serbia","Slovakia",
"Slovenia","Spain","Sweden","Switzerland","Turkey","Ukraine","United Kingdom","Vatican City"];
public filteredList = [];
public elementRef;
// NEW: added newly declared variable
public selectedIdx;
constructor(myElement: ElementRef) {
this.elementRef = myElement;
}
filter(event) {
if (this.query !== ""){
this.filteredList = this.countries.filter(function(el){
return el.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
}.bind(this));
// NEW: added new filter code
if (event.code == "ArrowDown" && this.selectedIdx == 0) {
this.selectedIdx--;
}
}else{
this.filteredList = [];
}
}
select(item){
this.query = item;
this.filteredList = [];
}
handleClick(event){
var clickedComponent = event.target;
var inside = false;
do {
if (clickedComponent === this.elementRef.nativeElement) {
inside = true;
}
clickedComponent = clickedComponent.parentNode;
} while (clickedComponent);
if(!inside){
this.filteredList = [];
}
}
// NEW: added new handleBlur function
handleBlur() {
if(this.selectedIdx > -1){
this.query = this.filteredList[this.selectedIdx];
}
this.filteredList = [];
this.selectedIdx = -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment