My Autocomplete shows the values from an object with this definition:
export class Person {
id: number;
name: string;
cityName: string;
}
This is the autocomplete template:
<mat-form-field class="example-full-width">
<input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
<mat-option *ngFor="let item of filteredOptions" [value]="item">
{{ item.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
And this is the displayWith function:
displayFn(value?: any) {
return value ? value.name : undefined;
}
It works, but the formControl binded to this autocomplete receives the entire item object:
{
id: 1;
name: "John";
cityName: "Dallas";
}
How can I get only the "id" value in the formControl ?
You have to do 2 things.
[value] bounds to id instead of the object.displayFn so that the passed in id is used to lookup the object and return the name which will then be displayed in the input.<mat-form-field class="example-full-width">
<input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
<mat-option *ngFor="let item of filteredOptions" [value]="item.id">
{{ item.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
displayFn(value?: number) {
return value ? this.filteredOptions.find(_ => _.id === value).name : undefined;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With