通常我有一个对象的对象 -> filteredDrivers
。
单个对象如下所示:
DRIVER_ID:99
DRIVER_NAME:“约翰·斯诺”
我在 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>
我想通过提交表单来传递整个对象,但在输入中我只想查看 driver.DRIVER_NAME。
如果我在输入中传递整个驱动程序,例如[value]="driver"
,我会看到[object Object]
表单提交给了我完整的对象
但是当我使用 [value]="driver.DRIVER_NAME"
时,我可以看到我想要的 - JOHN SNOW
但表单提交只给我 driver .DRIVER_NAME
如何通过提交表单来传递整个对象并在输入中仅查看 driver.DRIVER_NAME
属性?
最佳答案
Angular Material 文档中清楚地记录了 Autocomplete .
具体:
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>
关于javascript - 如何将整个对象传递给 md-autocomplete Angular 4 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45542952/