ItSolutionStuff.com

Angular Nl2br Pipe Example

By Hardik Savani β€’ May 2, 2024
Angular

Hi All,

I will explain step by step tutorial angular nl2br pipe. let’s discuss about nl2br pipe in angular. I’m going to show you about line break in angular. This post will give you simple example of angular new line in string.

In this post, i will example you how to replace \n to new line in angular. basically if you use nl2br function in php or other language.

Sometime we are storing data from textarea and use enter data using enter key and proper format data with line break but when we display that data it's now display with break like because we store \n on database. so it's not display properly, we can make it do using nl2br.

Here, we will create custom pipe for nl2br in angular project. you can use it in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 application.

Let's follow bellow step to resolve our problem.

Create Custom Pipe: src/app/nl2br.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({

name: 'nl2br'

})

export class nl2brPipe implements PipeTransform {

transform(value: string): string {

return value.replace(/\n/g, '<br/>');

}

}

Import Pipe: src/app/app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule } from '@angular/forms';

import { nl2brPipe } from './nl2br.pipe';

import { AppComponent } from './app.component';

@NgModule({

imports: [ BrowserModule, FormsModule ],

declarations: [ AppComponent, nl2brPipe ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

Update Component: src/app/app.component.ts

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

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

body = 'This is example. \none\ntwo';

}

Use Pipe in HTML: src/app/app.component.html

<p [innerHTML]="body | nl2br"></p>

Now you can run and see bellow output:

This is example.

one

two

I hope it can help you...

Tags: Angular
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Angular Material Radio Button Example

Read Now β†’
β˜…

10 Digit Mobile Number Validation in Angular

Read Now β†’
β˜…

Angular 9 File Upload Example

Read Now β†’
β˜…

Angular Toggle a Div on Button Click Example

Read Now β†’
β˜…

Angular Service with Httpclient Example

Read Now β†’
β˜…

How to Create New Component in Angular 8?

Read Now β†’
β˜…

How to Create Custom Pipe in Angular 9/8?

Read Now β†’