8

I've been trying to implement a custom <textarea> behavior wherein the enter event will fire a function and the ctrl+enter will trigger a newline on the <textarea>.

I've been trying to read through existing questions here, but most of them are using plunker and oddly enough i can't load them properly.

I've managed to make enter key submit something instead of doing a next line. However, when i do ctrl-enter keydown event, i can't seem to make textarea go to next line.

See this blitzstack for the sample.

lemoncodes
  • 2,371
  • 11
  • 40
  • 66

2 Answers2

13

I was able to make it work. Hopefully, this will give you a starting point. :)

Updated the triggerFunction to

 triggerFunction(event) {
        console.log(event);
        if (event.ctrlKey && event.key === 'Enter') {
          /*
            cannot make textarea produce a next line.
          */
          var text = document.getElementById("textarea1");
          text.value += '\n';
          console.log(text);
        //  text = text.

          console.log("next line!");
        } else if (event.key === 'Enter') {
          event.preventDefault();
          console.log("submit!");
        }
      }

And change html to

<div class="form-group">
    <label for="textarea1">Example textarea</label>
    <textarea 
      class="form-control"
      id="textarea1" 
      placeholder="Press Ctrl-Enter to do Next Line, otherwise Enter to Send"

      (keydown)="triggerFunction($event)"></textarea>
  </div>
Aslam
  • 9,204
  • 4
  • 35
  • 51
  • 1
    Ahh i understand, but one thing just to confirm, does `\n` in textarea actually exists when i passed the value of textarea to backend? via JSON or any other medium. im gonna try another approach instead of using `document` object, maybe im gonna use the model. i think in that way it is much for cleaner and uniformly follows angular conventions – lemoncodes Nov 01 '18 at 16:05
  • Yeah, you should do a clear version. I only wanted to put you in the right direction :) – Aslam Nov 01 '18 at 16:28
10

this is easier

(keydown.control.enter)="onCtrlEnter()"
James H
  • 531
  • 6
  • 15