gpt4 book ai didi

javascript - 如何将整个对象传递给 md-autocomplete angular 4 输入

转载 作者:行者123 更新时间:2023-11-29 19:02:55 24 4
gpt4 key购买 nike

通常我有一个对象的对象 -> 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com