Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 294
Jus10 Avatar asked Dec 11 '22 07:12

Jus10


2 Answers

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

like image 199
José Feliz Avatar answered Feb 18 '23 15:02

José Feliz


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!

like image 28
AnweshCR7 Avatar answered Feb 18 '23 15:02

AnweshCR7