Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Focus/Blur on Select programmatically (Angular6 Material)

Tags:

angular

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.

like image 291
Aeseir Avatar asked Jun 09 '18 05:06

Aeseir


1 Answers

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).

like image 60
Fateme Fazli Avatar answered Sep 20 '22 02:09

Fateme Fazli