Setting mat-autocomple value with values as objects and displayWith

54 Views Asked by At

I'm using mat-autocomplete in order to select an item. I'm populating the list with objects, so I have

<mat-form-field>
 <mat-label>my label</mat-label>
     <input type="text"
                     placeholder="Select"
                     matInput formControlName="myFormControl" 
                     [matAutocomplete]="myAC">
     <mat-autocomplete #myAC="matAutocomplete" 
                      [displayWith]="displayCodeDescriptionFn">
          <mat-option *ngFor="let option of itemsList$ | async" [value]="option">
                  {{option.code}} - {{option.description}}
          </mat-option>
     </mat-autocomplete>
</mat-form-field>

Please note that I'm making sure the itemsList$ is ready (i.e. loaded from the api) before I do anything else. Also, displayCodeDescriptionFn tries to display the option like this: "MyItemCode - SomeDescription"

everything works fine until I get data from the backend and I want to edit the values. Then the API is getting me the object I want to edit, but in this attribute, instead of the whole "Item" object, I'm getting only the "code". If I try to patchValue the field I see an "Undefined - Undefined". And that seems correct, since I only have the "code" coming from the backend. mat-select has a compareWith directive which is not available here. I do not want to go through the whole list of items just to get the actual object and then do patchValue with it. Is there a more elegant solution?

Thanks in advance.

0

There are 0 best solutions below