Angular Line Break in String | nl2br Pipe Angular

Hi All,

I am going to show you example of angular line break in string. you'll learn angular replace n with br. i would like to share with you angular replace newline with br. if you have question about replace n with br then i will give simple example with solution. You just need to some step to done angular nl2br pipe.

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 and angular 9 application.

Let's follow bellow step to resolve our problem.

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

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


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';


imports: [ BrowserModule, FormsModule ],

declarations: [ AppComponent, nl2brPipe ],

bootstrap: [ AppComponent ]


export class AppModule { }

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

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


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.



I hope it can help you...

April 26, 2020 | Category : Angular

Blog Search