简体   繁体   中英

How to pass whole object to input from md-autocomplete angular 4

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM