Search code examples
angularhighlightsetvaluemat-autocomplete

How to highlight option value in angular mat-autocomplete after setValue?


This is the maximum simplified code sample: https://stackblitz.com/edit/angular-8r153h-wcvefg?file=app/autocomplete-sample.ts

the problem is that: selected item is not highlighted in the list, when I manually set formControl value:

this.formControl.setValue("second");

Not highlighted item after setValue

but if I click on this item, then the item is highlighted:

Highlighted item

I see that highlight is when the option has mat-selected class.

Maybe have somebody any ideas on how to highlight that item after setValue?


Solution

  • autocomplete-sample.html

    <form>
      <mat-form-field>
        <input matInput [formControl]="formControl" [matAutocomplete]="autoComplete">
        <mat-autocomplete #autoComplete="matAutocomplete">
          <mat-option [ngClass]="(formControl.value===option.description)?'mat-selecte-default':''" *ngFor="let option of filteredOptions | async" [value]="option.description">
            {{option.description}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
    

    autocomplete-sample.css

    .mat-selected {
      background: darkblue !important;
      color: lightgray !important;
    }
    
    .mat-selecte-default {
      background: darkblue !important;
      color: lightgray !important;
    }
    

    Stackblitz example