Angular 2 Material 自动完成选定值

标签 angular autocomplete angular-material selectedvalue

我有自动完成输入

<div formArrayName="addresses"> 
  <div class="row" 
       *ngFor="let itemrow of searchForm.controls.addresses.controls; let i=index" 
       [formGroupName]="i">
    <mat-form-field>
      <input type="text" 
             class="form-control" id="address"
             formControlName="address" 
             matInput 
             [matAutocomplete]="auto"
             (keyup)="getESRI($event.target.value)"
             (focusout)="bindLocation($event.target.value)">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of testLocation"
                    [value]="option.text">
           {{ option.text }}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field> 
  </div>
</div>

"teSTLocation":[{"text":"Euronet","magicKey":"dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true},{"text":"Euronet","magicKey": "dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true}]

当我尝试添加值时 [value]="option.magicKey 当我选择选项时它显示在输入 option.magicKey 中。我需要 option.magicKey 仅作为值,option.text 作为输入选项。否则如何将 option.magicKey 作为参数添加到 bindLocation( $event.target.value) 函数?

最佳答案

使用'displayWith'

MatAutoComplete 具有一个名为 displayWith 的输入。其中,您需要传递一个函数,将您的选项的控制值映射到它的显示值。

这是一个例子:

<mat-form-field>

  <input
    matInput
    placeholder="Select a value"
    [formControl]="form.controls.enumField"
    [matAutocomplete]="autoComplete">

  <mat-autocomplete
    #autoComplete="matAutocomplete"
    [displayWith]="valueMapper">     <-- Using displayWith here

  <mat-option
    *ngFor="let enum of enumerationObservable | async"
    [value]="enum.key">
      {{ enum.value }}
  </mat-option>

</mat-autocomplete>

这是使用接收到的键返回值的函数

public valueMapper = (key) => {
  let selection = this.enumeration.find(e => e.key === key);
  if (selection)
    return selection.value;
};

关于Angular 2 Material 自动完成选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670491/

相关文章:

css - Angular Material 粘性 header 停止工作

javascript - Angular2 从子对象中调用观察者

c# - 在控制焦点上的 WPF 中打开 AutoCompleteBox

Angular 货币代码不适用于旧版 Angular 版本

javascript - Angularjs - 中止/取消运行 $http 调用

javascript - 如何制作 jquery ui-autocomplete 功能?

Angular 5使用 Material , Jasmine karma 测试失败,带有mat-icon

Angular Material 在与现有功能相同的组件中创建对话框

Angular TypeScript 将枚举与 Spring Boot 后端结合使用

angular - 是否可以使用 angular-cli 构建单独的 CSS 文件?