Angular 使用对象数组自动完成反应式表单
我有一个Multiselect,从数据库中得到一个对象数组,我需要Angular 使用对象数组自动完成反应式表单,angular,angular-reactive-forms,angular9,formgroups,Angular,Angular Reactive Forms,Angular9,Formgroups,我有一个Multiselect,从数据库中得到一个对象数组,我需要[displayWith]=''来显示所选对象的名称,但要存储所选对象的ID。 下面是HTML代码 <mat-form-field class="example-full-width"> <input type="text" placeholder="Customers" i18n-placeholder="customer
[displayWith]=''
来显示所选对象的名称,但要存储所选对象的ID。
下面是HTML代码
<mat-form-field class="example-full-width">
<input type="text"
placeholder="Customers"
i18n-placeholder="customerInput"
aria-label="customers"
matInput
[formControl]="customerControl"
formControlName="customerId"
(focus)="getCustomers(searchedCustomer)"
(change)="customerOnChange($event)"
[matAutocomplete]="autoCustomer">
<mat-autocomplete #autoCustomer="matAutocomplete" [displayWith]="displayCustomerName">
<mat-option *ngIf="customerloading"><span [ngTemplateOutlet]="loading"></span></mat-option>
<ng-container *ngIf="!customerloading">
<mat-option *ngFor="let customer of customerList" [value]="customer">
{{ customer.name }}
</mat-option>
</ng-container>
</mat-autocomplete>
</mat-form-field>
在所需的输入上,也可以是名称
,但在表单组
值
上,需要的只是id,而不是整个对象或名称
使用上述方法,结果显示整个对象,如下所示:
value:
customerId: {id: 226, name: "Abata", abbreviation: "Tazz", active: 0, number: 90, …}
我需要什么:
value:
customerId: 226
我尝试的是:
我试图改变现状
至[value]=“customer.id”
但是我没有从
[displayWith]=''中获取的名称`
我还尝试将customer.id转换为FormControll,而不是空字符串
this.contractForm = new FormGroup({
customerId: new FormControl(customer.id, [Validators.required]),
...
您应该在
component.ts
文件displaycustername
b中使用以下函数
collectionDisplayFn = (id: number) =>
Object.values(this.customerList).find(customer=> customer.id === id)?.name;
}
collectionDisplayFn = (id: number) =>
Object.values(this.customerList).find(customer=> customer.id === id)?.name;
}