How to replace string in angular 2?

Nimesh Vaghasiya picture Nimesh Vaghasiya · Jan 10, 2017 · Viewed 56.2k times · Source

I have used with below interpolation in html page.

<div>{{config.CompanyAddress.replace('\n','<br />')}}</div>

and also used

<div>{{config.CompanyAddress.toString().replace('\n','<br />')}}</div>

But both are showing text as below

{{config.CompanyAddress.replace('\n','<br />')}}
{{config.CompanyAddress.toString().replace('\n','<br />')}}

Answer

Siddharth Sharma picture Siddharth Sharma · Jan 10, 2017

You can use a pipe for the same:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replaceLineBreaks'})
export class ReplaceLineBreaks implements PipeTransform {
  transform(value: string): string {
    return value.replace(/\n/g, '<br/>');
  }
}

The pipe must be included in your @NgModule declarations to be included in the app. To show the HTML in your template you can use binding outerHTML.

<span [outerHTML]="config.CompanyAddress | replaceLineBreaks"></span>