Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent press enter from creating new line in Angular4

I have a textarea that I submit while pressing Enter

https://stackblitz.com/edit/angular-uvxifq-uyxteg

<textarea class="message-area" (keyup.enter)="ValidateCommentAndPost(commentErr, $event);" [(ngModel)]="comment" matInput #commentErr="ngModel"></textarea>

I would like to disable the new Line while I press enter, so I took some information on the web and did .

ValidateCommentAndPost(ngComment:NgModel, event?:KeyboardEvent){
    event.preventDefault();
    if((ngComment.invalid && (ngComment.dirty || ngComment.touched)) && ngComment.errors) {
        this.ResetComment();
    } else {
        this.PostComment();
    }
}

But this doesn't work, also, return false; still create a white line.

What can I do?

like image 411
Crocsx Avatar asked Dec 27 '18 05:12

Crocsx


1 Answers

Add event to capture enter and prevent the default behaviour. Add the keydown event to your component html

<textarea required
(keydown.enter)="onKeydown($event)" (keyup.enter)="ValidateCommentAndPost(commentErr, $event);" pattern="/^[/\S/]+$/i" [(ngModel)]="value" matInput #commentErr="ngModel"></textarea>

and add this to your component ts file

onKeydown(event){
      event.preventDefault();
    }
like image 68
Dinesh K Avatar answered Nov 03 '22 04:11

Dinesh K