2017-07-17 19 views
0

試圖實現與角Angular2自動建議給予明確的值

$ npm install ng2-auto-complete --save 

地圖添加和包裝自動建議到systemjs.config.js

map['ng2-auto-complete'] = 'node_modules/ng2-auto-complete/dist'; 
packages['ng2-auto-complete'] = { main: 'ng2-auto-complete.umd.js', ...] 

添加的組件

@Component({ 
    selector: 'person', 
    templateUrl: 'app/person/person.component.html' 
}) 
export class PersonComponent implements OnInit { 
    myForm: FormGroup; 
    staffInfo : PersonalMastModel[]; 
    public arrayOfKeyValues2: any[] = [ 
    {key:1, name:'Key One'}, 
    {key:2, name:'Key Two'}, 
    {key:3, name:'Key Three'}, 
    {key:4, name:'Key Four'} 
    ]; 
personalData(personName: String): Observable<DepartmentModel[]>{ 
     let headers = new Headers();   
      if(personName!= undefined){ 

       headers.append('Content-Type','application/json'); 
       headers.append('Access-Control-Allow-Origin', '*'); 
       return this.http.post(AppUtils.GET__MASTER_URL //return a list of department 
       ,{personName:personName} 
       ,{headers:headers}) 
       .map(response => response.json()) 
       .catch(this.handleError); 
      } 


    } 
............... 

在person.component.html中添加標籤

<input auto-complete [source]="arrayOfKeyValues2" 
     [(ngModel)]="model3" 
     placeholder="enter text" 
     value-property-name="key" 
     display-property-name="name"/>selected: {{model3 | json}}<br/><br/> 

這裏在下拉菜單中顯示未定義的(undefined)。 enter image description here

另外我怎樣才能改變這一點,以便每次都會從服務器端獲取數據。

回答

2

使用對象而不是字符串時,您需要使用list-formatter屬性來調用值格式化程序。

[list-formatter]="listFormatter" 
value-property-name="key" 
display-property-name="name"> 

,並定義爲listFormatter

listFormatter = (data: any) => `<span>(${data.key}) ${data.name}</span>`; 

這裏是一個工作Plunker例如與您的代碼。


  • 還怎麼我可以改變這一點,所以,每次將獲取從服務器端的數據?

可以使用valueChanged屬性將其綁定到從服務器獲取數據的功能,雖然這是一個完全獨立的問題。

+0

在提及的文檔中:valueChanged/ngModelChange,選擇新下拉列表時執行的回調函數。例如(valueChanged)=「myCallback($ event)」 - 在輸入時從下拉列表中選擇新值時調用。 – Rosh

+0

是的,是不是你想要的?你在你的回調函數中調用服務器! –

+0

不,不在Onselect上,它的按鍵更多 – Rosh