Angular 2材质自动完成选定值

时间:2017-12-06 09:08:30

标签: 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)函数?

3 个答案:

答案 0 :(得分:7)

使用'displayWith'

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

以下是一个例子:

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>

答案 1 :(得分:1)

[displayWith] 属性与自动完成字段一起使用。

HTML文件

<input
  type="text"
  placeholder="Address"
  mdInput
  formControlName="address" 
  [mdAutocomplete]="auto"
  (keyup)="onKeyUp()">
<md-autocomplete
  #auto="mdAutocomplete"
  [displayWith]="displayFn">
  <md-option *ngFor="let option of options"
    [value]="option">
    {{ option.text }}
  </md-option>
</md-autocomplete>

答案 2 :(得分:0)

<mat-option>有事件 onSelectionChange ,通过此事件,您可以调用任何函数并绑定选项对象中的所有内容

(onSelectionChange)="bindLocation(option.text, option.magicKey)"