[英]Reactive forms mat-autocomplete with array of objects
I have a Multiselect and getting an array of objects back as a result from the DB I need the [displayWith]=""
to show the name of the selected object but to store the ID of the selection.我有一个多选并从数据库中获取一组对象我需要[displayWith]=""
来显示所选 object 的名称,但要存储选择的 ID。 here is the HTML Code这是 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>
in this case, the customer list is an array of objects like在这种情况下,客户列表是一个对象数组,例如
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, …}
on the input needy so be the name
but on the formGroup
> value
needs to be just the id not the whole object or the name.在输入需要所以是name
,但在formGroup
> value
需要只是 id 而不是整个 object 或名称。
with the approach above the value results show the whole object., like so:使用上述方法,值结果显示整个 object.,如下所示:
value:
customerId: {id: 226, name: "Abata", abbreviation: "Tazz", active: 0, number: 90, …}
WHAT ID NEED:需要什么身份证明:
value:
customerId: 226
What I tried:我尝试了什么:
I tried to change the <mat-option *ngFor="let customer of customerList" [value]="customer">
to [value]="customer.id' but then I don't get the name of from
[displayWith]=""`我试图将<mat-option *ngFor="let customer of customerList" [value]="customer">
更改为[value]="customer.id' but then I don't get the name of from
=""`
I also tried to at the customer.id to the FormControll instead of an empty string我还尝试在 customer.id 到 FormControll 而不是空字符串
this.contractForm = new FormGroup({
customerId: new FormControl(customer.id, [Validators.required]),
...
you should be using the below function in your component.ts
file displayCustomerName
b您应该在您的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.