0

I have code like below

<ng-container>
  <ng-container>
    <div class="class1" tabindex="0" [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger">
      <div class="customclass">
        <i class="fa fa-bell-o"></i>
        <h2>Main Menu</h2>
      </div>
    </div>
  </ng-container>

<mat-menu #menu="matMenu" class="myClass" >
    <div class="Custom">      
        <div mat-menu-item (click)="$event.stopPropagation()" (keydown)="myFunc($event)"
         <div class="class2">
      <h3>Label</h3>     
        <div class="class3">
        <p> some text, <a href="link address">first link</a>.
            Some Test text and link <a href="address" >second link</a>
        </p>
      </div>
        </div>      
    </div>
  </mat-menu>

I want to navigate through links with the Tab key. So, I have added tabindex like below

 let myLinks = this.elRef.nativeElement.getElementsByTagName('a');
   
    for (let i = 0; i <= anchors.length-1; i++) {
      myLinks[i].setAttribute('tabindex', '0');
   }

myFunc(event: { stopPropagation: () => void }) {event.stopPropagation();}

I want to close the menu when I press shift+tab from the first link. or when I press the tab key after the last link inside the menu.

Also, when I shift+tab from the first link, focus should be on the Main Menu, and when I press the tab key after the last link, focus should be set on the next element.

How do I achieve it?

Explorer
  • 161
  • 1
  • 4
  • 16

1 Answers1

1

You shouldn’t try to achieve this, and we’d need to know more about your use case to suggest a correct pattern.

A menu in ARIA’s sense is reserved for desktop-like applications.

The keyboard control you describe is not the expected behaviour of a menu, in which arrow keys should be used to navigate between the menu items. According to Keyboard navigation in Angular Material’s Menu documentation, this is already the case.

Tab only sets focus onto the menu once, the next Tab will quit the menu. This is what ARIA calls a composite widget.

According to the Angular Material documentation, you should put <button> elements inside the menu.

As per ARIA standard, the only roles allowed inside a menu are group, menuitem, menuitemcheckbox, menuitemradio and separator.

heading (<h3>) or paragraph (<p>) are not allowed.

What to use instead

To align ARIA and Angular Material, the most appropriate component is probably Sidenav.

The ARIA Authoring Practices Guide (APG) suggest a Disclosure Navigation Menu for navigation, instead of a menu.

Although this example uses the word "menu" in the colloquial sense to refer to a set of navigation links, it does not use the WAI-ARIA menu role.

Their example works both with Tab keys, and arrow keys.

If you prefer to continue using the <mat-menu> component, you should change it’s role. Be careful to get the roles right, though.

Andy
  • 4,783
  • 2
  • 26
  • 51