![](/img/trans.png)
[英]nesting a custom component that contains a mat-autocomplete in reactive forms
[英]Reactive forms mat-autocomplete with array of objects
我有一个多选并从数据库中获取一组对象我需要[displayWith]=""
来显示所选 object 的名称,但要存储选择的 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 而不是整个 object 或名称。
使用上述方法,值结果显示整个 object.,如下所示:
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
=""`
我还尝试在 customer.id 到 FormControll 而不是空字符串
this.contractForm = new FormGroup({
customerId: new FormControl(customer.id, [Validators.required]),
...
您应该在您的component.ts
文件displayCustomerName
b 中使用以下 function
collectionDisplayFn = (id: number) =>
Object.values(this.customerList).find(customer=> customer.id === id)?.name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.