Angular 2材质自动完成选定值

问题描述 投票:3回答:3

我有自动完成输入

<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)函数中?

angular autocomplete angular-material selectedvalue
3个回答
7
投票

Use '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;
};

1
投票

将[displayWith]属性与auto complete字段一起使用。

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>

0
投票

<mat-option>有事件onSelectionChange,有了这个事件,你可以调用任何函数并绑定来自option对象的所有东西

(onSelectionChange)="bindLocation(option.text, option.magicKey)"
© www.soinside.com 2019 - 2024. All rights reserved.