簡體   English   中英

反應性 forms mat-autocomplete 與對象數組

[英]Reactive forms mat-autocomplete with array of objects

我有一個多選並從數據庫中獲取一組對象我需要[displayWith]=""來顯示所選 object 的名稱,但要存儲選擇的 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 而不是整個 object 或名稱。

使用上述方法,值結果顯示整個 object.,如下所示:

value:
customerId: {id: 226, name: "Abata", abbreviation: "Tazz", active: 0, number: 90, …}

需要什么身份證明:

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 =""`

我還嘗試在 customer.id 到 FormControll 而不是空字符串

  this.contractForm = new FormGroup({
      customerId: new FormControl(customer.id, [Validators.required]),
...

您應該在您的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM