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>
2
Answers
Please write this code on ngOnInit, we need to make the API call inside
displayWith
If you are using angular 16+ you can use signals here
you can also return function like this
Also if
this.freespins$
isBehaviourSubject
you can get the value without subscribingcheck the example here
https://stackblitz.com/edit/bdx7mn?file=src%2Fexample%2Fautocomplete-display-example.ts,src%2Fexample%2Fautocomplete-display-example.html