Reputation: 287
Generally i have an object of objects -> filteredDrivers
.
Single object looks like this:
DRIVER_ID: 99
DRIVER_NAME: "JOHN SNOW"
which i'm using in md-autocomplete:
<md-input-container>
<input type="text"
name="driver"
mdInput
[mdAutocomplete]="auto"
placeholder="Driver"
ngModel
>
</md-input-container>
<md-autocomplete #auto="mdAutocomplete">
<md-option *ngFor="let driver of filteredDrivers| async" [value]="driver"
ngDefaultControl>
{{ driver.DRIVER_NAME}}
</md-option>
</md-autocomplete>
And i want to pass whole object by submitting a form but in input i want to view just driver.DRIVER_NAME.
If i pass whole driver like [value]="driver"
in input i see [object Object]
and form submit gives me full object
but when i go with [value]="driver.DRIVER_NAME"
i can see what i want - JOHN SNOW
but form submit gives me only driver.DRIVER_NAME
How can i pass whole object by submitting the form and see only driver.DRIVER_NAME
property in input?
Upvotes: 2
Views: 1512
Reputation: 3671
It's clearly documented in the Angular Material docs for Autocomplete.
Specifically:
Setting separate control and display values
If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the actual text field), you'll need to set the displayWith property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties.
To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's displayWith property.
<md-input-container> <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto"> </md-input-container> <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn"> <md-option *ngFor="let option of filteredOptions | async" [value]="option"> {{ option.name }} </md-option> </md-autocomplete>
Upvotes: 3