保存并绑定到下拉选择的 Id,但在 Angular Material 中显示值
Save and bind to the Id of a drop-down selection, but display the Value in Angular Material
这可能是一个答案非常简单的愚蠢问题,但经过一个星期的编码后,我感到很沮丧,无法弄清楚。
如何绑定到选择的 ID,但显示该值的字符串表示形式?即,我有一个显示客户名称的下拉列表,但我想保存 Id
以供数据库使用。
我的选择项有两个属性:customer.Display
(名称)和customer.Id
。
如何进行绑定以将我的 Id 保存到 [(ngModel)]="loadDataService.selectedLoad.CustomerId
,但在下拉列表中显示我的 Display(它已经显示 Display,因此被覆盖):
<mat-form-field>
<input type="text" placeholder="Customer Search" id="CustomerId" name="CustomerId" aria-label="Number" matInput [formControl]="myCustomerSearchControl"
[matAutocomplete]="auto" [(ngModel)]="loadDataService.selectedLoad.CustomerId" (keyup)="onCustomerSearch($event)">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let customer of customerArray" [value]="customer.Display">
{{ customer.Display }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
当你使用自动完成时,你有一个 optionSelected
事件。您需要使用它来找到您选择的选项。
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="setServiceId($event)">
...
</mat-autocomplete>
然后,在您的组件中,您必须实现该功能:
setServiceId(dislay: string) {
const id = this.customerArray.find(c => d.Display === display).id;
this.loadDataService.selectedLoad.CustomerId = id;
}
这种做法假设您有独特的客户展示。如果没有,就需要用到这个函数,用前面的HTML + 这个HTML :
setServiceId(customer: any) {
this.loadDataService.selectedLoad.CustomerId = customer.id;
}
这可能是一个答案非常简单的愚蠢问题,但经过一个星期的编码后,我感到很沮丧,无法弄清楚。
如何绑定到选择的 ID,但显示该值的字符串表示形式?即,我有一个显示客户名称的下拉列表,但我想保存 Id
以供数据库使用。
我的选择项有两个属性:customer.Display
(名称)和customer.Id
。
如何进行绑定以将我的 Id 保存到 [(ngModel)]="loadDataService.selectedLoad.CustomerId
,但在下拉列表中显示我的 Display(它已经显示 Display,因此被覆盖):
<mat-form-field>
<input type="text" placeholder="Customer Search" id="CustomerId" name="CustomerId" aria-label="Number" matInput [formControl]="myCustomerSearchControl"
[matAutocomplete]="auto" [(ngModel)]="loadDataService.selectedLoad.CustomerId" (keyup)="onCustomerSearch($event)">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let customer of customerArray" [value]="customer.Display">
{{ customer.Display }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
当你使用自动完成时,你有一个 optionSelected
事件。您需要使用它来找到您选择的选项。
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="setServiceId($event)">
...
</mat-autocomplete>
然后,在您的组件中,您必须实现该功能:
setServiceId(dislay: string) {
const id = this.customerArray.find(c => d.Display === display).id;
this.loadDataService.selectedLoad.CustomerId = id;
}
这种做法假设您有独特的客户展示。如果没有,就需要用到这个函数,用前面的HTML + 这个HTML :
setServiceId(customer: any) {
this.loadDataService.selectedLoad.CustomerId = customer.id;
}