Gieted
Gieted

Reputation: 895

How to focus input element when Menu is opened?

enter image description here

<button mat-button id="categories-button" [mat-menu-trigger-for]="categoryList">
  <span>categories</span>
  <mat-icon id="drop-arrow">arrow_drop_down</mat-icon>
</button>
<mat-menu #categoryList>
  <mat-form-field appearance="standard" id="category-search-wrapper">
    <input (click)="$event.stopPropagation()" matInput id="category-search">
  </mat-form-field>

  <button mat-menu-item>Settings</button>
  <button mat-menu-item>Help</button>
</mat-menu>

I want category-search input to be focused, when Menu is opened, the problem is it doesn't seem to be ready yet, when menuOpened event is emitted. How can I focus input element when Menu is opened?

Upvotes: 3

Views: 6129

Answers (2)

Gieted
Gieted

Reputation: 895

<button
  id="categories-button"
  [mat-menu-trigger-for]="categoryList"
  (menuOpened)="categorySearch.focus()"
>
  <span>categories</span>
  <mat-icon id="drop-arrow">arrow_drop_down</mat-icon>
</button>
<mat-menu #categoryList>
  <mat-form-field #categorySearch appearance="standard" id="category-search-wrapper">
    <input matInput (click)="$event.stopPropagation()" />
  </mat-form-field>

  <button mat-menu-item>Settings</button>
  <button mat-menu-item>Help</button>
</mat-menu>
  1. Add (menuOpened)="this.categoryListOpened()" to the button, that opens the Menu
  2. Declare categoryListOpened method in your component's class like above

Upvotes: 3

Radik
Radik

Reputation: 2795

you can use ViewChild as follow

<button mat-button
  (menuOpened)="menuOpened()"
  [matMenuTriggerFor]="menu">Menu
</button>

<mat-menu #menu="matMenu">
  <mat-form-field appearance="standard" id="category-search-wrapper">

    <input
      #search
      (click)="$event.stopPropagation()" matInput>

  </mat-form-field>

  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>


export class AppComponent  {

  @ViewChild('search', {static: false})
  inputElement: ElementRef;

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

example

Upvotes: 3

Related Questions