角度材料2 md-autocomplete动态名称

时间:2017-09-28 13:29:59

标签: angular-material2

在文档中说明您必须创建类似的md-autocomplete:

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

有没有办法在运行时生成#auto?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您最好的选择是将其包裹在这样的*ngFor中,以便模板变量的范围仅限于for loop次迭代,

<ng-container *ngFor="let autocomplete of autocompletes">

  <!-- Input -->
  <md-form-field>
    <input type="text"
        mdInput
        [formControl]="autocomplete.control"
        [placeholder]="autocomplete.placeholder"
        [mdAutocomplete]="auto">
  </md-form-field>

  <!-- Autocomplete -->
  <md-autocomplete #auto="mdAutocomplete">
    <md-option *ngFor="let option of autocomplete.options" [value]="option">
      {{ option }}
    </md-option>
  </md-autocomplete>

</ng-container>

autocompletes = [
  { placeholder: 'Sample 1', options: [1, 2, 3], control: new FormControl() },
  { placeholder: 'Sample 2', options: [3, 4, 5], control: new FormControl() },
  { placeholder: 'Sample 3', options: [6, 7, 8], control: new FormControl() },
];

请参阅此EXAMPLE