0

This might be a stupid question with a very simple answer, but after a week of coding I feel fried and can't figure it out.

How can I bind to the Id of a selection, but display the string representation of the value? I.e., I have a drop-down that display the names of Customers, but I want to save the Id for DB purposes.

My selection item has two properties: customer.Display (Name), and customer.Id.

How can I do the binding to save my Id to [(ngModel)]="loadDataService.selectedLoad.CustomerId, but display my Display in the drop-down (it already displays the Display, so that is covered):

<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>
4

1 回答 1

1

当您使用自动完成时,您有一个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;
}
于 2018-03-12T07:35:30.660 回答