Angular Material Autocomplete - how to select option

Viewed 1609

I am using Angular material autocomplete and I am trying to select value using @Input and form control. Almost everything is working fine. I am setting value using input like this:

@Input() set startingPointValue(value) {
  this.control.setValue(value, { emitEvent: false });
  this.resizeInput();
}

And the value of the input is properly set but when I open autocomplete, an option which should be selected don't have mat-selected class so basically there is no indication which option was selected and this is confusing. When I click same option again class is added.

Is there a way to do that using setValue or I need to use something else?

This is my autocomplete HTML:

<mat-form-field class="starting-point-filter-container">
  <mat-label>{{ label }}</mat-label>
  <input
    id="inputStartingPoint"
    #startingPointInput
    matInput
    placeholder="Type to filter results"
    type="text"
    [formControl]="control"
    [matAutocomplete]="startingPointAutocomplete"
    spellcheck="false"
  />
  <mat-icon class="starting-point-icon--dropdown">arrow_drop_down</mat-icon>
</mat-form-field>

<mat-autocomplete
  #startingPointAutocomplete="matAutocomplete"
  [displayWith]="displayName"
  (opened)="scrollToSelected()"
>
  <perfect-scrollbar class="select-scrollbar" [config]="scrollBarConfig" #scrollFilterContainer>
    <mat-optgroup
      *ngFor="let group of groups"
      [label]="group.name"
      [class.mat-optgroup-no-label]="!group.name"
      class="starting-point-group-container"
      #scrollToContainer
    >
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option.id }}
      </mat-option>
    </mat-optgroup>
  </perfect-scrollbar>
</mat-autocomplete>

Any help will be appreciated

Edit: I created StackBlitz with autocomplete: https://stackblitz.com/edit/angular-ivy-mqwwky. You can inspect option number 2 after init. There is no class .mat-selected on it. You need to click it manually to set it properly. Question is how to do that during init?

0 Answers
Related