物料自动完成:将多个文本输入链接到一个自动完成面板

时间:2018-07-24 06:15:40

标签: angular angular-material angular-material2

问题

如何将多个文本输入链接到一个autocomplete panel

用例

给出一个包含多个耦合字段的表格:电话号码(<input>);电话说明/标签(<input [matAutocomplete]>)。用户应选择先前输入的电话描述/标签之一。

技术挑战

根据official example<mat-autocomplete><input>必须互相引用,例如

<mat-form-field>
  <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option>
</mat-autocomplete>

如果此类元素是在循环中生成的,例如

<div *ngFor="let item of items; index as index">
    ...
</div>

无法动态生成mat-autocomplete ID时。

1 个答案:

答案 0 :(得分:0)

If all you want to do is link multiple input fields to one autocomplete panel, it's as simple as this - stackblitz

Markup

<form class="example-form">
  <mat-form-field class="example-full-width" *ngFor="let autoComplete of autoCompletes">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
  </mat-form-field>
  <mat-autocomplete #auto ="matAutocomplete">
    <mat-option *ngFor="let option of options" [value]="option">
      {{option}}
    </mat-option>
  </mat-autocomplete>
</form>

Code

export class AutocompleteSimpleExample {
  myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  autoCompletes = ['batman', 'superman'];
}

Or do you want to have multiple input field/autocomplete panel pairs? That would have to be done within the template as template variables are static-only.