首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >自定义按钮组件在enter上不起作用

自定义按钮组件在enter上不起作用
EN

Stack Overflow用户
提问于 2020-10-03 16:58:39
回答 1查看 106关注 0票数 1

在我的Angular项目中,我有一个自定义按钮组件,我在整个应用程序中都使用它作为提交-表单-按钮。

问题是,当用户想要在网站上提交任何表单时,当焦点位于pro button component上时,Enter键不起作用。

这是我的pro-button组件:

代码语言:javascript
运行
复制
<ng-template [ngIf]="stroked" [ngIfElse]="normalButton">
  <button
    mat-stroked-button
    [color]="color"
    [type]="type"
    [disabled]="disabled"
    tabindex="-1"
    #theButton
  >
    <ng-content></ng-content>
  </button>
</ng-template>
<ng-template [ngIf]="stroked" #normalButton>
  <button
    mat-raised-button
    [color]="color"
    [type]="type"
    [disabled]="disabled"
    tabindex="-1"
    #theButton
  >
    <ng-content></ng-content>
  </button>
</ng-template>

请注意,我知道角度伪事件,并且知道像这样的东西可能会起作用:

代码语言:javascript
运行
复制
<pro-button
     color="primary"
     type="submit"
     (keydown.enter)="onSubmit()"
     #submitButton
>
   submit
</pro-button>

但是我在我的项目中经常使用pro-button component,我不认为将(keydown.enter)="onSubmit()"添加到我所有的pro-button选择器中是一种好的做法。

EN

Stack Overflow用户

回答已采纳

发布于 2020-10-03 21:01:21

我通过将以下代码添加到pro-button.component.ts文件修复了此问题:

代码语言:javascript
运行
复制
  @ViewChild('theButton') theButton: any;

  constructor(private renderer: Renderer2, private el: ElementRef) {
    (el.nativeElement as HTMLElement).tabIndex = 0;
  }

 @HostListener('keydown.enter', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if(this.type === 'submit' && !this.disabled) {
      this.getButtonElement().click();
    };
  }

  private getButtonElement(): HTMLButtonElement {
    return (
      this.theButton.nativeElement || this.theButton._elementRef.nativeElement
    );
  }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64182453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档