具有对象数组的反应形式垫自动完成

问题描述 投票:0回答:1

我有一个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, …}

需要什么ID:

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
1个回答
0
投票

您应该在component.ts文件displayCustomerName b中使用以下功能

collectionDisplayFn = (id: number) =>
    this.customerList.find(customer=> customer.id === id)?.name;
}
© www.soinside.com 2019 - 2024. All rights reserved.