I have some simple Angular 7.x code that basically uses a contenteditable div where I am trying to prevent the default action when a user presses the [ENTER] key - the code appears fine but no matter what I seem to try it does the default action e.g moves the cursor to the next line which I am trying to prevent from happening.
What am I doing wrong?
// component code
onTextChange(event): void {
// keyCode for the Enter key is 13
if (event.keyCode === 13) {
console.log('enterPressed');
event.stopPropagation();
event.preventDefault();
}
}
// template code
<div contenteditable="true" [(ngModel)]="text" (keyup)="onTextChange($event)" (change)="onTextChange($event)" #textarea></div>
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Notes. Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.. You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.. Specifications
As noted below, calling preventDefault () for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent (), without specifying cancelable: true has no effect. Toggling a checkbox is the default action of clicking on a checkbox.
preventDefault() is a method that cancels the default action that belongs to the event, which in submit button’s case is to reload the page, what you were doing was that you were adding preventDefault() method to a function (addEventItemObject) and not the submit button’s (addEventBtn) click event. 1 Like
Use keypress
or keydown
, which is caught at the moment user presses key, instead of "after" user has already pressed the key. Also you should get an error in console trying to use ngModel
on a div. You can catch the value with $event.target.innerText
instead:
onTextChange(event): void {
// keyCode for the Enter key is 13
if (event.keyCode === 13) {
console.log('enterPressed', event.target.innerText);
event.preventDefault();
}
}
Template:
<div contenteditable="true" (keydown)="onTextChange($event)">
STACKBLITZ
In Angular, you can directly use it like (keydown.enter)="$event.preventDefault()"
<div contenteditable="true" [(ngModel)]="text" (keydown.enter)="$event.preventDefault()" #textarea></div>
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