I have an autocomplete in my angular reactive form.
I want to display myObject.name but use myObject.id as value.
When the form is prefilled with existing values, I need to get myObject.name base on myObject.id which takes some time. So unfortunately, what is shown in the autocomplete is an id and not a name. I can’t make it work.
I tried with observable but it looks like displayWith does not support it. How can I do that ?
Typescript :
public displayWith(id: string): string {
if (!id) {
return '';
}
let freespinName = '';
this.freespins$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(freespins => {
const found = freespins.find((freespin: Freespin) => freespin.id === id);
freespinName = found?.name || id;
});
return freespinName;
}
HMTL :
<mat-label>Freespin</mat-label>
<input type="text"
placeholder="Select a freespin"
matInput
formControlName="rewardId"
[matAutocomplete]="auto">
<mat-autocomplete requireSelection #auto="matAutocomplete"
[displayWith]="displayWith.bind(this)">
<mat-option *ngFor="let freespin of filteredFreespins[i] | async"
[value]="freespin.id">
{{freespin.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>