How to enable focus on input element inside mat-select component?

Advertisements

I need to activate the cursor on the html input element (search field) using keyboard inside mat-select.

It works perfectly fine when using mouse, but because of WCAG requirements I need to make it fully working using keyboard.

https://stackblitz.com/edit/angular-dukfxf?file=src%2Fapp%2Fapp.component.ts

I’ve tried almost everything from custom js code to Angular directives.

Any thougths?

>Solution :

You can do the following:

1. Add an identification to your input and use the event openedChange from mat-select

<mat-select (openedChange)="focus()">
  <input
    ...
    #exampleInput
   />
</mat-select>

2. Define the function focus() in your component and it would work

export class AppComponent {
  @ViewChild('exampleInput') searchElement: ElementRef;
  ...

  focus() {
    setTimeout(() => {
      this.searchElement.nativeElement.focus();
    }, 0);
  }
}

https://stackblitz.com/edit/angular-nscqdp?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

Leave a ReplyCancel reply