Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular stop Enter Key from submitting

I am trying to stop the Enter from submitting my button and rather make it point to another function. I tried trapping the Enter via the Host Listener and then do preventDefault() on it to stop it from firing.

My template in my component looks like this:

<mat-dialog-content class="dialog-content">{{data.content | translate}}</mat-dialog-content>
<div>
  <mat-button-toggle-group>
    <button type="button" matDialogClose (click)="dialogRef.close()">{{uppercase }}</button>
    <button type="button" (click)="dialogRef.close(true)" cdkFocusInitial>{{uppercase}}</button>
  </mat-button-toggle-group>
</div>

At the top of my component code:

export enum KEY_CODE {
  ENTER_KEY = 13
}

Inside my export class:

@HostListener('window:keyup', ['$event'])
keyEventUp(event: KeyboardEvent) {

    if (event.keyCode === KEY_CODE.ENTER_KEY) {
      event.preventDefault();
      event.stopPropagation();
      return false;
    }
}
like image 312
user1019042 Avatar asked Apr 24 '18 20:04

user1019042


2 Answers

DOM events carry a payload of information named $event. It's possible to use it on any input event, i.e. (input),(keydown), (click), etc.

It's possible to skip the use of the Hostlistner and apply preventDefault on $event, like so:

(keydown.enter)="$event.preventDefault()"

on the buttons:

...
<button ... (keydown.enter)="$event.preventDefault()" ...>...</button>
...

or:

HTML:

...
<button ... (keydown.enter)="prevent($event)" ...>...</button>
...

Typescript:

...
prevent(event){
 event.preventDefault();
}
...

Demo

like image 63
Vega Avatar answered Oct 24 '22 05:10

Vega


If you are using a form you can prevent it over all using keydown.enter event in the main tag:

<form [formGroup]="..." (keydown.enter)="$event.preventDefault()">
...
</form>

But maybe you want also to prevent some other keys combinations like:

(keydown.enter)="$event.preventDefault()"
(keydown.shift.enter)="$event.preventDefault()"
(keydown.control.enter)="$event.preventDefault()"
(keydown.alt.enter)="$event.preventDefault()"
like image 26
Juan Antonio Avatar answered Oct 24 '22 07:10

Juan Antonio