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

标签 javascript angular angular-material2

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

相关文章:

javascript - 搜索和替换旧背景颜色

javascript - 表单验证不适用于 <select>

Javascript - 使用 setTimeOut() promise 执行 "background proccessing"

angular - SSR - Angular Universal 9 加载我的根两次并挂起

javascript - 如何在 Typescript 中扩展组件,并找出所需的参数?用例 : Angular - extending mat-side-nav

JavaScript 日期和年份

javascript - 将字符串作为函数参数传递并将其用作 object.assign 中的动态键名

Angular - 根据变量变化触发事件

当表单域处于事件状态时,Angular Material 表单域轮廓输入颜色会发生变化

angular - Material 2 : extending MatInput