Crocsx
Crocsx

Reputation: 7640

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?

Upvotes: 4

Views: 8131

Answers (1)

Dinesh K
Dinesh K

Reputation: 651

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();
    }

Upvotes: 22

Related Questions