【问题标题】:How to stop <mat-expansion-panel> from triggering with spacebar?如何阻止 <mat-expansion-panel> 用空格键触发?
【发布时间】:2018-08-04 02:18:01
【问题描述】:

我在面板描述中有一个带有 textarea 框的 mat-accordion。当我在文本区域中绑定并点击空格键时,它会打开/关闭面板。我怎样才能阻止这种情况?

<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>

【问题讨论】:

  • 您的标记的标题中没有输入框。您可以编辑问题以包含它吗?
  • 是的,我的意思是文本区域和面板描述,尽管无论是在标题区域还是描述区域,问题都是一样的
  • 我可以在标题中使用文本区域但在描述中无法重现问题。
  • 对我来说,两者都是这样做的,所以我确信解决方案可能是相同的。
  • 在 mat-expansion-panel-header 中包含 mat-panel-description 不是正确的方法吗?其实我不知道这是否能解决任何问题,但这看起来不对

标签: html angular input material-design


【解决方案1】:

我找到了一种更干净的解决方案。仅将此添加到面板标题以覆盖 keydown 事件 SPACE:

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


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

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

【讨论】:

  • 我总是反对在模板中添加逻辑。然而,这个解决方案很棒。不需要控制器中的附加功能,也不需要只关注空格键的条件代码。干得好。
  • 在我这边让它工作的是:&lt;mat-panel-title (keydown.Space)="$event.stopPropagation()"&gt;
【解决方案2】:

你在你的 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>

.js中的函数会这样,

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

您现在可以在 div 内的任何元素中使用空间,而不会导致展开面板关闭。希望这会有所帮助!

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2022-06-24
      • 2019-03-09
      • 2020-02-11
      • 1970-01-01
      相关资源
      最近更新 更多