How to replace string in angular 2?

I used bottom interpolation on the html page.

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

and also used

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

But both show the text below

 {{config.CompanyAddress.replace('\n','<br />')}} {{config.CompanyAddress.toString().replace('\n','<br />')}} 
+6
source share
2 answers

You can use the same channel:

 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 ads for inclusion in the app. To show HTML in your template, you can use outerHTML binding.

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

{{}} - to interpolate strings, and the result will always be added as String. Binding does not work at all in this case due to the < and > contained in the expression, {{}} not interpreted as expected.

 <div [innerHTML]="replaceLineBreak(config.CompanyAddress) | safeHtml"></div> 

from

 replaceLineBreak(s:string) { return s && s.replace('\n','<br />'); } 

should do what you want. As already mentioned, @hgoebl replaceLineBreak can be implemented as a pipe if you need it in several places.

Plunger example

Tip . It is not recommended to directly contact methods, because the method is called in every change detection cycle. A clean (default) channel is called only when the input value changes. Therefore, the pipe is more efficient.

Another way is to replace only once and bind to a value with replaced line breaks, rather than repeating replaceLineBreak .

Tip . You probably want to replace all line breaks, not just the first ones. one. There are enough JS questions that explain how to do this, so I was not worried.

+7
source

Source: https://habr.com/ru/post/1013932/


All Articles