angularformsautocompleteangular-materialmat-autocomplete

Mat-Autocomplete multiple fields


I am using Mat-Autocomplete but for some reason it only works when I am using 1 field, when I add another second field something strange happens.

Both on field 1 as in field 2 I get the same options in my dropdown, these options are the options who should only be available when I edit field 2.

Is it even possible to have more than 1 field, I never see any examples on this matter.

FIELD1

<div class="col input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text">Sender</span>
  </div>
  <mat-form-field>
  <input matInput [matAutocomplete]="auto" type="text" class="form-control" (ngModelChange)="change()" [(ngModel)]="terms[sender]" [ngModelOptions]="{standalone: true}">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let document of documents" [value]="document._source.field.Sender">
      <span>{{document._source.field.Sender}}</span>
    </mat-option>
  </mat-autocomplete>
  </mat-form-field>
</div>

FIELD2

    <div class="col input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text">Receiver</span>
  </div>
  <mat-form-field>
    <input matInput [matAutocomplete]="auto" type="text" class="form-control" (ngModelChange)="change()" [(ngModel)]="terms[receiver]" [ngModelOptions]="{standalone: true}" >
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let document of documents" [value]="document._source.field.Receiver">
        <span>{{document._source.field.Receiver}}</span>
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</div>

Solution

  • The two autocomplete have the same name auto, they need to have different names:

    <input matInput [matAutocomplete]="auto1"...
    <mat-autocomplete #auto1=...
    ...
    <input matInput [matAutocomplete]="auto2"...
    <mat-autocomplete #auto2=...