0
votes

I have functionality where user types something and press submit button then the cursor should move to next line. When user types some words and press Enter key cursor should shift to next line with in the textarea. I am trying to achieve this functionality using KeyBoardEvent by using keypress event with keycode for Enter key. Below is the code, HTML code

<textarea #elRef id="language" class="post-text-area badge-post-textarea focus ng-pristine ng- 
untouched ng-valid ng-empty" placeholder="Share your thoughts..." [(ngModel)]="content"></textarea>
<button (click)="submit()"></button>

The below angular code is where once user clicks submit I creating one keyevent for Enter and dispatch that event but Enter key event is not happening. ANGULAR JS code

  @ViewChild('elRef', { static: false }) userInput: ElementRef;
  
  submit(){
    const event = new KeyboardEvent('keypress', { 'keyCode': 32 });
    this.userInput.nativeElement.dispatchEvent(event);
    return;
   }

Kindly, Please some one help on this

2
You simply want the cursor to move to next line on enter click in a text area? But that is the normal behavior you don't need to implement it - Sudipto Mukherjee
@SudiptoMukherjee Please check now just updated question with errors. Actually when user types something in text area and press submit button cursor should move to next line on pressing submit button. - Karthik

2 Answers

0
votes

After a bit of thought there is a much simpler approach to your problem without creating any key event. Since there is a two way binding in the text area we can manipulate the variable to do the same ( simply by adding '\n' at the end of the string ). Working sample

If of any assistance please make sure you mark this as answer. Happy Coding :)

0
votes

(keypress)="yourFunction($event)" is the general function which will take care of using the keyboard events

So along with (click) add (keypress)" too!

You can use (keypress.enter)="yourFunction($event)" which will take care of the enter functionality.

What you have is (click)="yourFunction()" is basically, writing a Mouse Click event which in hindsight is not the correct way to handle keypress event

Now, if you want your functionality to be specific to keyup or keydown, you can use these

(keyup.enter)="yourFunction($event)" (keydown.enter)="yourFunction($event)"