2017-04-20 60 views
1

這裏是一個簡單的問題,我找不到解決方案。我在輸入中有一個typeahead指令讓用戶選擇一個類別(類別數組示例 - > [{id:1as1d,name:'some category'},...]ngx-bootstrap typeahead FormControl angular 2

如何將id值設置爲FormControl字段(它將出現在提交的表單中)並在輸入上顯示名稱(在用戶選擇時將在輸入中顯示該名稱)?有沒有辦法分離發送表單中的內容和什麼是被顯示在使用FormControl?

我只能找到一種方法來顯示和設置相同的變量或者只ID或唯一的名字。

<input 
    formControlName="category" 
    [formControl]="userForm.controls['category']" 
    [typeahead]="categoriesObservable" 
    (typeaheadLoading)="toggleLoadingCategories($event)" 
    (typeaheadNoResults)="toggleNoCategoriesFound($event)" 
    (typeaheadOnBlur)="categoryFieldSelected($event)" 
    (typeaheadOnSelect)="categoryFieldSelected($event)" 
    typeaheadOptionsLimit="7" 
    typeaheadOptionField="name" 
    placeholder="Choose a category" 
    class="form-control"/> 

回答

2

你想噸什麼o do是使用選項的模板。

http://valor-software.com/ngx-bootstrap/#/typeahead從文檔摘自:

<ng-template #customItemTemplate let-model="item" let-index="index"> 
    <h5>This is: {{model | json}} Index: {{ index }}</h5> 
</ng-template> 

<pre class="card card-block card-header">Model: {{selected | json}}</pre> 
<input [(ngModel)]="selected" 
    [typeahead]="states" 
    [typeaheadItemTemplate]="customItemTemplate" 
    class="form-control"> 

在這個例子中customItemTemplate用於顯示模型和索引,但該模型的任何屬性都可以使用。在選擇時,可以發送選擇的整個對象,然後在發送給你的函數中,可以將id從對象中取出並用於任何需要的對象。

+0

我會盡快嘗試一下,謝謝! – MattJ

1

您可以像使用模板一樣在首選答案中選擇要在下拉菜單中顯示選項的方式,並使用功能categoryFieldSelected(v: any)來選擇在選擇其中一個選項時發生的情況。這樣,輸入字段將具有所選類別的id +名稱的值,但selectedCategoryCode將是您在提交表單時使用的值。

private selectedCategoryCode: string = ''; 

categoryFieldSelected(v: any): void { 
this.selectedCategoryCode = v.item.id; 
this.form.get('category').setValue(v.item.id+' '+v.item.name); 
} 
0

這聽起來很瘋狂,但留在我身邊。

只需使用提交表單的隱藏輸入,並在事件typeaheadOnSelect將id值分配給隱藏輸入。

在加載數據(編輯舊數據)的情況下,只需使用類別id來獲取文本並將名稱值分配給預先輸入。

不要忘記在typeaheadOnSelect事件的隱藏輸入上使用control.updateValueAndValidity()

相關問題