【问题标题】:Reactive forms mat-autocomplete with array of objects带有对象数组的反应形式垫子自动完成
【发布时间】:2020-04-27 18:56:53
【问题描述】:

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

需要什么身份证件:

value:
customerId: 226

我尝试了什么:

我试图改变 &lt;mat-option *ngFor="let customer of customerList" [value]="customer"&gt;[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】:

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

    collectionDisplayFn = (id: number) =>
        Object.values(this.customerList).find(customer=> customer.id === id)?.name;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 2021-12-10
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多