lemoncodes
lemoncodes

Reputation: 2421

Angular TextArea behavior bind to Ctrl-Enter Key

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.

Upvotes: 9

Views: 7230

Answers (2)

James H
James H

Reputation: 629

this is easier

(keydown.control.enter)="onCtrlEnter()"

Upvotes: 15

Aslam
Aslam

Reputation: 9672

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>

Upvotes: 13

Related Questions