Home > Blockchain >  Mat-menu default focus an item from the list
Mat-menu default focus an item from the list

Time:10-13

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>

CodePudding user response:

It is not recommended due to the accessibility. If visually impaired user open a menu he expect his focus is on the first menu item.

source: https://www.w3.org/WAI/ARIA/apg/example-index/menu-button/menu-button-links#kbd_label

CodePudding user response:

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

  • Related