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;
}
}
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
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()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With