2017-05-05 72 views
0

問題試圖找到在角2

這裏使用的輸入做自動完成的正確方法是我的自動完成組件,當我們輸入的東西它得到相關的結果,因爲我接受,但困難的是,我用這個自動完成在表格中輸入很多時間,數據也通過網絡服務。

目前,我認爲有什麼方法可以使代碼更加緊湊和動態,所以可以多次使用,因爲我們需要緊湊的方式?

**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; 
    } 

回答

0

您需要使用自定義的指令進行autocomplete.Like低於

var app = angular.module('YourModule',[]); 
app.directive('autoComplete', function($timeout) { 
return function(scope, iElement, iAttrs) { 
     iElement.autocomplete({ 
      source: scope[iAttrs.uiItems], 
      select: function() { 
       $timeout(function() { 
        iElement.trigger('input'); 
       }, 0); 
      } 
     }); 
}; 
});