Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 832
lemoncodes Avatar asked Nov 01 '18 14:11

lemoncodes


People also ask

What is keydown event in angular?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is textarea in angular?

<textarea> elements inside an AngularJS application are given certain classes. These classes can be used to style textarea elements according to their state. The following classes are added: ng-untouched The field has not been touched yet. ng-touched The field has been touched.


2 Answers

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>
like image 109
Aslam Avatar answered Sep 27 '22 22:09

Aslam


this is easier

(keydown.control.enter)="onCtrlEnter()"
like image 42
James H Avatar answered Sep 27 '22 23:09

James H