Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Checkbox inside expansion panel header: how to allow the checkbox to be activated with the keyboard?

I have a checkbox inside the expansion panel header and for accessibility reasons the checkbox needs to be functional for keyboard-only users. However, if you tab to focus on the checkbox, pressing space or enter doesn't check/uncheck the checkbox, but expands the panel instead. I am struggling to fix this issue since these are angular material components and I am not sure how they work under the hood.

How can I allow the checkbox to be checked/unchecked with the keyboard?

Here is some html that demonstrates the problem when rendered:

<mat-expansion-panel>
  <mat-expansion-panel-header>
    <mat-checkbox color="primary">Label</mat-checkbox>
  </mat-expansion-panel-header>
  Content
</mat-expansion-panel>

And here is a demo, if you tab to the checkbox pressing space or enter does not check/uncheck it.

https://stackblitz.com/edit/angular-4rmq9v

like image 828
phelhe Avatar asked Oct 29 '25 01:10

phelhe


1 Answers

To prevent the keyboard and mouse events from reaching the expansion panel, you can call $event.stopPropagation() in the keydown and click event handlers of the checkbox:

<mat-expansion-panel>
  <mat-expansion-panel-header>
    <mat-checkbox color="primary" 
      (click)="$event.stopPropagation()" 
      (keydown)="$event.stopPropagation()" >
        Label
    </mat-checkbox>
  </mat-expansion-panel-header>
  Content
</mat-expansion-panel>

See this stackblitz for a demo.

like image 68
ConnorsFan Avatar answered Oct 30 '25 18:10

ConnorsFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!