Material 自动完成:Link 多个文本输入到一个自动完成面板

Material Autocomplete: Link multiple text inputs to one autocomplete panel

问题:

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

用例

给定一个包含多个耦合字段的表单:phone number (<input>); phone description/label (<input [matAutocomplete]>)。用户应选择先前输入的 phone description/label.

之一

技术挑战

根据 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 时。

如果您只想link将多个输入字段输入一个自动完成面板,就这么简单 - stackblitz

标记

<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>

代码

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

或者您想要多个输入 field/autocomplete 面板对吗?这必须在模板中完成,因为模板变量是静态的。