Search code examples
javascriptangulardom-eventskeyup

event.preventDefault() appears to not work for me within a contenteditable div


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>

Solution

  • 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