Angular stop Enter Key from submitting
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()"
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