这是一个我找不到解决方案的简单问题。我在输入中有一个 typeahead 指令,它允许用户选择一个类别(类别数组示例 -> [{ id: 1as1d, name: 'some category'},...]
如何将 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"/>
最佳答案
您要做的是使用选项模板。
摘自 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 并将其用于您需要的任何东西。
关于javascript - ngx-bootstrap typeahead with FormControl angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43529417/