Angular mat-autocomplete doesn't work with options returned by function

Viewed 832

I have took autocomplete example from Material official web site and changed getting options from variable of component class to function, options display but I can't select anything, clicking on drop-down doesn't select a value.

Here is sample project on StackBlitz.

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of options()" [value]="option">
    {{option.value}}
  </mat-option>
</mat-autocomplete>

export class AutocompleteSimpleExample {
  myControl = new FormControl();
  options(): KeyValue[] {
    return [{ key: "1", value: "One" }];
  }
}
interface KeyValue {
  key: string;
  value: string;
}
1 Answers

Since the data source of ngFor returned by function, Clicking mat-option trigger a change detection, which cause ngFor to get a new array and generate a new mat-option due to which the selection is not working. you can prevent this by using trackBy function

component.html

 <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options();trackBy:trackByIdentity" [value]="option">
        {{option.value}}
      </mat-option>
    </mat-autocomplete>
    <!-- #enddocregion mat-autocomplete -->
  </mat-form-field>

component.ts

trackByIdentity:TrackByFunction<{key:string,value:string}> = (index: number, item: any) => item.key;

Working Example

Related