Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string in angular 2?

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 />')}}
like image 403
Nimesh Vaghasiya Avatar asked Jan 10 '17 07:01

Nimesh Vaghasiya


Video Answer


1 Answers

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>
like image 151
Siddharth Sharma Avatar answered Sep 18 '22 22:09

Siddharth Sharma