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

2k views Asked by At

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?

2

There are 2 answers

0
Tony On BEST ANSWER

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

0
Kavinda Senarathne On

You could pass the value of stateCtrl, and add that to your condition to check if value exists there as well:

<span [innerHTML]="state.name | highLight: toHighlight : stateCtrl.value"></span>

and then do the additional check for that value:

transform(text: string, search: string, ctrlValue: string): string {
  // ....
  return (search && ctrlValue) ? text.replace(regex, match => `<b>${match}</b>`) : text;
}