![](/img/trans.png)
[英]using ngx-bootstrap typeahead in angular 5 with an array of model values
[英]ngx-bootstrap typeahead with FormControl angular 2
這是一個簡單的問題,我找不到解決方案。 我在輸入中有一個typeahead指令,該指令可讓用戶選擇一個類別(類別數組示例-> [{id:1as1d,名稱:'some category'},...]
如何設置id值到FormControl字段(將出現在提交的表單中)並在輸入中顯示名稱(在用戶選擇時顯示在輸入中)? 有沒有一種方法可以分隔使用FormControl時發送的表單中的內容和顯示的內容?
我只能找到一種方法來顯示和設置僅id或name相同的變量。
<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"/>
您要做的是使用模板作為選項。
取自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,並將其用於所需的任何對象。
您可以像在上一個答案中那樣使用模板來選擇要在下拉菜單中顯示選項的方式,並使用功能categoryFieldSelected(v: any)
選擇在選擇其中一個選項時會發生什么。 這樣,輸入字段將具有所選類別的id + name的值,但是selectedCategoryCode
將是您提交表單時使用的值。
private selectedCategoryCode: string = '';
categoryFieldSelected(v: any): void {
this.selectedCategoryCode = v.item.id;
this.form.get('category').setValue(v.item.id+' '+v.item.name);
}
這聽起來會很瘋狂,但請和我在一起。
只需對提交表單使用隱藏的輸入,然后在typeaheadOnSelect
事件中將ID值分配給隱藏的輸入。
在加載數據(編輯舊數據)的情況下,只需使用類別ID即可獲取文本並將名稱值分配給預輸入。
不要忘記在typeaheadOnSelect
事件中的隱藏輸入上使用control.updateValueAndValidity()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.