Search code examples
angularangular-material

Mat-menu default focus an item from the list


I have a mat-menu with several options. If opened, it focuses or highlights the first item in the list. How can I have it focus/highlight an item of my choice - say the 3rd item?

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
  <button mat-menu-item>Item 3</button>
  <button mat-menu-item>Item 4</button>
</mat-menu>

Solution

  • Add a template ref to the menu item element you want to focus then using the @ViewChild get the element ref, then when the menu is opened set the focus to the menu item with the focusItem template ref

    <button mat-button [matMenuTriggerFor]="menu" (menuOpened)="menuOpened()">
      Menu
    </button>
    
    <mat-menu #menu="matMenu">
      <button mat-menu-item>Item 1</button>
      <button mat-menu-item>Item 2</button>
      <button mat-menu-item #focusItem>Item 3</button>
      <button mat-menu-item>Item 4</button>
    </mat-menu>
    
    @ViewChild('focusItem')
    menuItemElement: MatMenuItem;
    
    menuOpened() {
      this.menuItemElement.focus('keyboard');
    }
    

    P.S. I am using the latest angular material version