Search code examples
javascriptangularform-submitevent-delegation

Custom button component doesn't work on enter


In my Angular project, I have a custom button component that I have used as a submit-form-button all throughout the application.

The problem is when the user wants to submit any of the forms on the website, the enter key does not work when focus is on the pro button component.

This is my pro-button component:

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

Kindly note that I'm aware of Angular pseudo-events and know that something like this will probably work:

<pro-button
     color="primary"
     type="submit"
     (keydown.enter)="onSubmit()"
     #submitButton
>
   submit
</pro-button>

But I'm using pro-button component in my project a lot and I don't think it's good practice to keep adding (keydown.enter)="onSubmit()" to all of my pro-button selectors.


Solution

  • I fixed the issue by adding this bit of code to the pro-button.component.ts file:

      @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
        );
      }