0

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?

4

2 回答 2

1

您可以传递 的值stateCtrl,并将其添加到您的条件中以检查值是否也存在:

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

然后对该值进行额外检查:

transform(text: string, search: string, ctrlValue: string): string {
  // ....
  return (search && ctrlValue) ? text.replace(regex, match => `<b>${match}</b>`) : text;
}
于 2020-11-24T23:54:51.260 回答
1

自动完成-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>

自动完成-sample.css

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

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

Stackblitz 示例

于 2020-11-25T03:50:04.987 回答