Home > Software engineering >  How can I lose focus in mat-autocomplete?
How can I lose focus in mat-autocomplete?

Time:12-21

I need to remove the focus from the angular mat-autocomplete component when one of the options is selected. When an option is selected, in mat-form-field appears the class mat-focused that I can not remove in any way.

My component:

<mat-form-field  appearance="fill" #matFormField>
  <mat-label>{{ label }}</mat-label>
    <div fxLayout="row">
      <input
        #elementInput
        (focusout)="unFocusOnSearchControl(elementInput.value)"
        type="text"
        matInput
        [matAutocomplete]="auto"
        [formControl]="myControl"
        placeholder="Míni 3 characters"
        autofocus
      />
      <mat-icon *ngIf="icono" matSuffix>search</mat-icon>
    </div> 
  <mat-autocomplete
    #autocomplete
    #auto="matAutocomplete"
    autoActiveFirstOption
    (optionSelected)="unFocusOnSearchControl($event.option.value)" 
  >
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option[field]">
      {{ option[field] | translate }}
    </mat-option>
  </mat-autocomplete>
  <mat-hint> {{ subtext | translate }}</mat-hint>
</mat-form-field>

Is there any way to force the loss of focus when working with angular material?

CodePudding user response:

When unFocusOnSearchControl method is called blur the input element

unFocusOnSearchControl(e){
  this.elementInput.nativeElement.blur()
}
  • Related