Hello Devs, 

In this tutorial, we will learn Angular Line Break in String | nl2br Pipe Angular

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.

Follow this step by step guide below. 



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>


May this example help you.