Make selected mat-option as active with checkmark

417 Views Asked by At

I am using mat-autocomplete, from the dropdown when manually one of the option is selected, the selected item is indicated with different bg color and a checkmark on right side.

But when one of the dropdown item is pragmatically set, the item is not highlighted. I use setValue() to programmatically to set the value.

1

There are 1 best solutions below

0
Alireza On

1- Add a new property to your data model like:

options: {key:string,isSelected:boolean}[] = [{key:'One',isSelected:false},{key:'Two',isSelected:false},{key:'Three',isSelected:false}];

2- Add the [displayWith] property to mat-autocomplete to work with the function that helps us to set/get value to mat-option

<mat-autocomplete requireSelection #auto="matAutocomplete"  [displayWith]="displaySelectedData()">

3- Use a function to bind data to mat autocomplete

displaySelectedData = () => (value: string): string =>{return !value ? this.fetchedData :  value}

fetchedData is the default value e.g. this.fetchedData = "Four"

4- Add ngClass to mat-option

<mat-option  [ngClass]="{'myClass': option.isSelected}" 

then

.myClass {background-color: var(--mat-option-selected-state-layer-color)}

5- Now the option that already had data has a new style. finally if want to add a checkbox to your option just use the material checkbox in the mat-option tag.

6- Finally you should change options object isSelected value to true | false to manage ngClass changes. use (optionSelected)='method($event)' on mat-autocomplete to change options object property value.