【发布时间】:2020-04-27 18:56:53
【问题描述】:
我有一个 Multiselect 并从数据库中返回一个对象数组,我需要 [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>
在这种情况下,客户列表是一个对象数组,例如
0: {id: 94, name: "Abata", abbreviation: "Npath", active: 0, number: 54, …}
1: {id: 443, name: "Abata", abbreviation: "Wikido", active: 0, number: 36, …}
2: {id: 226, name: "Abata", abbreviation: "Tazz", active: 0, number: 90, …}
在输入需要时,name 但在 formGroup > value 需要只是 id 而不是整个对象或名称。
用上面的方法,值结果显示整个对象。,像这样:
value:
customerId: {id: 226, name: "Abata", abbreviation: "Tazz", active: 0, number: 90, …}
需要什么身份证件:
value:
customerId: 226
我尝试了什么:
我试图改变
<mat-option *ngFor="let customer of customerList" [value]="customer"> 到 [value]="customer.id'
but then I don't get the name of from[displayWith]=""`
我还尝试将 customer.id 设置为 FormControll 而不是空字符串
this.contractForm = new FormGroup({
customerId: new FormControl(customer.id, [Validators.required]),
...
【问题讨论】:
标签: angular angular-reactive-forms angular9 formgroups