简体   繁体   中英

Reactive forms mat-autocomplete with array of objects

I have a Multiselect and getting an array of objects back as a result from the DB I need the [displayWith]="" to show the name of the selected object but to store the ID of the selection. here is the HTML Code


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

in this case, the customer list is an array of objects like

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, …}

on the input needy so be the name but on the formGroup > value needs to be just the id not the whole object or the name.

with the approach above the value results show the whole object., like so:

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

WHAT ID NEED:

value:
customerId: 226

What I tried:

I tried to change the <mat-option *ngFor="let customer of customerList" [value]="customer"> to [value]="customer.id' but then I don't get the name of from [displayWith]=""`

I also tried to at the customer.id to the FormControll instead of an empty string

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

you should be using the below function in your component.ts file displayCustomerName b

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM