Remove Focus/Blur on Select programmatically (Angular6 Material)

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


Try this Template

<input #autoCompleteInput type="text" [matAutocomplete]="auto"/>

component

@ViewChild('autoCompleteInput', { read: MatAutocompleteTrigger }) autoComplete: MatAutocompleteTrigger;

  close() {
    this.autoComplete.closePanel();
  }

Plunker

Tags:

Angular