I duplicated the Angular 6 Material autocomplete simple example: Simple Autocomplete
I am trying to figure out how remove focus once selection has been made.
I have added the following change:
In HTML
<mat-autocomplete #autoGroup="matAutocomplete" (optionSelected)="onSelectionChanged($event)">
In Components
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
}
After it outputs the value to console i would like to remove the focus from the input field, but not sure the way to do this.
the mat-focused
class of mat-form-field causes the focus on mat-auto-complete, by removing it from mat-form-field it will be not focused,
in 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);
}
}
in 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>
check this stackblitz.
Building on answer as per Aeseir's findings
Link @ViewChild to your input.
export class WhateverComponent {
@ViewChild('textInput') textInput: ElementRef;
//all other code
}
in onSelectionChanged function
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
// blur will remove focus on the currently selected element
this.matInputMain.nativeElement.blur();
// if you using form you can wipe the input too
this.yourForm.reset();
}
The above will log the selected value to console, blur the focus and reset the form (if you using form and want this function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With