简体   繁体   中英

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>

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

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!

你也可以使用这个较短的版本:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM