ngx-bootstrap typeahead与FormControl angular 2

问题描述 投票:1回答:3

这是一个我无法找到解决方案的简单问题。我在输入中有一个typeahead指令,允许用户选择一个类别(类别数组示例 - > [{id:1as1d,name:'some category'},...]

如何将id值设置为FormControl字段(将出现在提交的表单中)并在输入上显示名称(在用户选择时将在输入中显示)?有没有办法分离发送表单中的内容以及使用FormControl时显示的内容?

我只能找到一种方法来显示和设置相同的变量,只有id或only 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"/>
javascript angular2-forms ngx-bootstrap
3个回答
4
投票

您要做的是使用模板作为选项。

取自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从对象中取出并将其用于您需要的任何内容。


2
投票

您可以像在一个流行的答案中一样使用模板来选择在下拉列表中显示选项的方式,并使用函数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获取文本并将名称值分配给预先输入。

不要忘记在control.updateValueAndValidity()事件的隐藏输入上使用typeaheadOnSelect

© www.soinside.com 2019 - 2024. All rights reserved.