Prevent New Line In Angular Text Box

Avoid Line Break

Sometimes you may need to prevent line break in the comment or remark section where an HTML input element <textarea/> is used. Generally as you type in the text area and press ENTER key to put the next part of string in the new line and it may cause some issues in other activities. For example, your input string from text area is saved into (Oracle) database and while you copy the string or text, where one or more line breaks found, and paste it some where else then your whole string may not appear in the same line and it makes a problematic for some situations for further processing in business flow.

Prerequisites

Angular 15.0.3, npm 8.19.2, node 18.12.1

How to create Angular project

Text Area

A simple <textarea/> HTML tag is used to create a text area element in the web page. So write the below code into src/app/app.component.html file.

The following code will just show a text area input field where you can type as you wish and you can even press ENTER key from your keyboard to insert a line break in the text.

<div class="content" role="main">

	<textarea id="comment" rows="4"></textarea>

</div>

<router-outlet></router-outlet>

therefore, the above code snippets will not prevent you from inserting a line break in the string or text you type in the text area.

Now let’s add onEnterKeyPress() function on ENTER key down to avoid any line break or new line using the ENTER key into the text you type. So, after adding onEnterKeyPress() function to the textarea tag:

<div class="content" role="main">

	<textarea id="comment" rows="4" (keydown.enter)="onEnterKeyPress($event)"></textarea>

</div>

<router-outlet></router-outlet>

The actual implementation of onEnterKeyPress() function is written into the type script file src/app/app.component.ts.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Prevent New Line Text Box';
  
  onEnterKeyPress(event: any){
      event.preventDefault();
  }
}

So, the onEnterKeyPress() function prevents the default functionality of the ENTER key and user will not be allowed to insert any line break or new line into the text which is typed into the text area.

If type any is not specified in the onEnterKeyPress() function then, you will see the following error:

Error: src/app/app.component.ts:11:13 - error TS7006: Parameter 'event' implicitly has an 'any' type.

11   onEnterKeyPress(event){

Testing Application

When you do not have onEnterKeyPress() function implementation on ENTER key down.

prevent new line text

After preventing new line by implementing onEnterKeyPress() function in the textarea:

prevent new line text

Hope it gave an idea to you to disallow a new line in the text.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *