如何解决自定义按钮组件在输入时不起作用
在Angular项目中,我有一个自定义按钮组件,在整个应用程序中,我一直将其用作提交表单按钮。
问题是,当用户想要在网站上提交任何表单时,当焦点位于pro button component
上时,enter键不起作用。
这是我的pro-button
组件:
<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>
请注意,我知道Angular伪事件,并且知道类似的事情可能会起作用:
<pro-button
color="primary"
type="submit"
(keydown.enter)="onSubmit()"
#submitButton
>
submit
</pro-button>
但是我在项目中经常使用pro-button component
,并且我不认为继续向所有(keydown.enter)="onSubmit()"
选择器中添加pro-button
是一种好习惯。
解决方法
我通过将以下代码添加到pro-button.component.ts
文件中解决了该问题:
@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
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。