Multiple autocomplete in same page with different source in angular 4 with angular material

Nawab Ahmad picture Nawab Ahmad · Aug 29, 2017 · Viewed 16k times · Source

Multiple autocomplete in same page with different source in angular 4 with angular material:

source :https://material.angular.io/components/autocomplete/examples

I have followed the material autocomplete example and trying to add one more autocomplete in the same page but the source is different but not working.

Is formcontrol is creating problem ??

Answer

Faisal picture Faisal · Aug 29, 2017

You have the same reference variable (#auto) assigned to both inputs. The id needs to be unique for each input. Change your second input and md-autocomplete to following:

<md-input-container>
  <input mdInput placeholder="Test" [mdAutocomplete]="autoTest" [formControl]="testCtrl">
</md-input-container>
<md-autocomplete #autoTest="mdAutocomplete">
  <md-option *ngFor="let test of filteredTests | async" [value]="test">
    {{ test }}
  </md-option>
</md-autocomplete>

Link to Plunker Demo


For cycles like *ngFor there is no need to create dynamically named template variable, since

Template reference variables are scoped to the template they are defined in. A structural directive creates a nested template and, therefore, introduces a separate scope. (This question)