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.
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.
<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.
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>
this is easier
(keydown.control.enter)="onCtrlEnter()"
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