I am currently using the mat-autocomplete
feature and I am trying to remove focus from the input after selecting an element without needing a click. The mat-focused
class within the mat-form-field
is responsible for focusing on the mat-auto-complete
. By removing it from the mat-form-field
, I was able to achieve this. However, there is a slight delay in setting the mat-focused
class and I have been using setTimeout
to wait for it to be set before removing it. Although this works, I believe there might be a better solution utilizing async functions, promises, observables, or other features provided by Angular Material instead of relying on setTimeout
.
Component:
export class AutocompleteSimpleExample {
myControl: FormControl = new FormControl();
public matForm ;
constructor(){
}
ngOnInit(){
this.matForm = document.getElementById("matForm")
}
options = [
'One',
'Two',
'Three'
];
test(option){
console.log(option)
setTimeout(function(){
this.matForm.classList.remove('mat-focused' )}, 100);
}
}
HTML:
<form class="example-form">
<mat-form-field class="example-full-width test" #matForm id="matForm">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" #textInput>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="test($event.option)">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
You can view the example on StackBlitz.