问题
这是我的自动填充组件,当我输入相关结果时我会接受,但困难在于我在表单中多次使用自动完成输入,而且数据也通过网络服务获取。
目前,我认为有没有办法让代码更紧凑,更动态,所以它可以按照我们想要的方式多次使用?
**here my html**
<input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter($event) (blur)="handleBlur()">
<div class="suggestions" *ngIf="filteredList.length > 0">
<ul>
<li *ngFor="let item of filteredList;let idx = index" [class.complete-selected]="idx == selectedIdx"
(mousedown)="select($event,item)">
{{item}}
</li>
</ul>
以下是我在组件中的逻辑
getCityList(){
this.cityService.getCity()
.subscribe(
city => this.onCityListSuccess(city),
error => this.onCityListError(error));
}
onCityListSuccess(result: any) {
this.cityList=result.city;
console.log(this.cityList);
}
onCityListError(error: any) {
this.errorService.message(error);
}
public query = '';
public countries:any=[];
filteredList:any =[];
elementRef:any;
selectedIdx: number;
a:any[];
filter(event: any) {
console.log(event);
if (this.query !== "") {
this.countries=this.cityList;
this.filteredList = this.countries.filter(function (el:any) {
return (el.toLowerCase().substr(0,this.query.length) === this.query.toLowerCase()) == true;
}.bind(this));
if (event.code == "ArrowDown" && this.selectedIdx < this.filteredList.length) {
this.selectedIdx++;
} else if (event.code == "ArrowUp" && this.selectedIdx > 0) {
this.selectedIdx--;
}
} else {
this.filteredList = [];
}
}
select(event:any,item:any) {
this.query = item;
this.filteredList = [];
this.selectedIdx = -1;
event.stopPropagation();
}
handleBlur() {
if (this.selectedIdx > -1) {
this.query = this.filteredList[this.selectedIdx];
}
this.filteredList = [];
this.selectedIdx = -1;
}
handleClick(event:any) {
var clickedComponent = event.target;
var inside = false;
do {
if (clickedComponent === this.elementRef.nativeElement) {
inside = true;
}
clickedComponent = clickedComponent.parentNode;
} while (clickedComponent);
if (!inside){
this.filteredList = [];
}
this.selectedIdx = -1;
}