How to replace string in angular 2?
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>
{{}}
is for string interpolation and the result will always be added as String. The binding doesn't work at all in this case because of the <
and >
contained in the expression, the {{}}
are not interpreted as expected.
<div [innerHTML]="replaceLineBreak(config.CompanyAddress) | safeHtml"></div>
with
replaceLineBreak(s:string) {
return s && s.replace('\n','<br />');
}
should do what you want. As mentioned by @hgoebl replaceLineBreak
could be implemented as pipe as well if you need it at several places.
Plunker example
Hint: It's discouraged to bind to methods directly, because the method is called at every change detection cycle. A pure (default) pipe is only called when the input value changes. Therefore a pipe is more efficient.
Another way is to do the replacement only once and bind to the value with the replaced line breaks instead of calling replaceLineBreak
repeatedly.
Hint: You probable want to replace all line breaks, not only the first. one. There are enough JS questions out there that explain how to do that, therefore I didn't bother.