'How to stop <mat-expansion-panel> from triggering with spacebar?

I have a mat-accordion with a textarea box in the panel-description. When I am tying in the text area and hit spacebar it opens/closes the panel. How can I stop this?

<mat-accordion>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      Header
    </mat-expansion-panel-header>
    <mat-panel-description>
      <mat-form-field>
        <textarea matInput></textarea>
      </mat-form-field>
    </mat-panel-description>
  </mat-expansion-panel>
</mat-accordion>


Solution 1:[1]

I found one solution more clean. Only add to panel-header this for override keydown event SPACE:

(keydown.Space)="$event.stopImmediatePropagation();"


<mat-expansion-panel-header (keydown.Space)="$event.stopImmediatePropagation();">

Ref: https://github.com/angular/components/blob/master/src/material/expansion/expansion-panel-header.ts

Solution 2:[2]

You do something like this in your html,

<mat-accordion>
 <mat-expansion-panel>
  <div (keydown)="handleSpacebar($event)">
   /*this div should contain elements inside of the mat-expansion-panel
   where you would like to stop the propagation of the space key press*/             
  </div>
 </mat-expansion-panel>
</mat-accordion>

The function in the .js will be as so,

handleSpacebar(ev) {
 if (ev.keyCode === 32) {
   ev.stopPropagation();
 }
}

You can now use space in any of the element inside the div without causing the expansion panel to close. Hope this helps!

Solution 3:[3]

You could also use this shorter version:

<div (keydown.Space)="$event.stopPropagation()">

Solution 4:[4]

add (keydown.enter)="$event.preventDefault()" to parent element

<mat-expansion-panel>
    <mat-expansion-panel-header>
   .....
   </mat-expansion-panel-header>
   <div class="panel-body" (keydown.enter)="$event.preventDefault()">
   ....
   </div>
</mat-expansion-panel>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AdrianHHH
Solution 2 AnweshCR7
Solution 3 Daniel Sauvé
Solution 4 Deepu Reghunath