Search code examples
angularangular-materialaccessibility

mat-radio-button not getting focus inside a mat-menu


I have a menu where the user can change the language, and has other options like sign out and settings. I want to make this menu accessible using the keyboard. The problem it is only working for the mat-menu-item and not for the mat-radio-buttons. The radio buttons are not getting focused at all.

When adding mat-menu-item directive to the mat-radio-button, I get the following error:

More than one component is matched on this element: MatMenuItem ([mat-menu-item]) and MatRadioButton (mat-radio-button)

Here is a stackblitz


Solution

  • You can add the radio button options as separate menu items and programmatically set the value for the radio buttons when the menu is selected.

    The code is given below

    menu-icons-exampe.html

    <button mat-icon-button [matMenuTriggerFor]="menu" aria-label="Example icon-button with a menu">
      <mat-icon>more_vert</mat-icon>
    </button>
    <mat-menu #menu="matMenu">
      <button mat-menu-item style="height: fit-content;" (click)="language=1">
      <mat-radio-group class="grid">
        <mat-radio-button value="1" [checked]="language==2">Option 1</mat-radio-button>
    
      </mat-radio-group>
      </button>
       <button mat-menu-item style="height: fit-content;" (click)="language=2">
      <mat-radio-group class="grid" >
        <mat-radio-button value="2" [checked]="language==2">Option 2</mat-radio-button>
    
      </mat-radio-group>
      </button>
      <button mat-menu-item>
        <mat-icon>dialpad</mat-icon>
        <span>Redial</span>
      </button>
      <button mat-menu-item>
        <mat-icon>voicemail</mat-icon>
        <span>Check voice mail</span>
      </button>
      <button mat-menu-item>
        <mat-icon>notifications_off</mat-icon>
        <span>Disable alerts</span>
      </button>
    </mat-menu>

    and in your component declare a variable "language" as shown below

    menu-icons-example.ts

    @Component({
      selector: 'menu-icons-example',
      templateUrl: 'menu-icons-example.html',
      styleUrls: ['./menu-icons-example.scss']
    })
    export class MenuIconsExample {
      public language: any
    }