javascript - 如何替换 Angular 2中的字符串?

标签 javascript angular string-interpolation

我在 html 页面中使用了以下插值。

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

也用过

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

但两者都显示如下文字

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

最佳答案

你也可以使用管道:

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

管道必须包含在您的@NgModule 声明中才能包含在应用程序中。 要在您的模板中显示 HTML,您可以使用绑定(bind) outerHTML。

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

关于javascript - 如何替换 Angular 2中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563283/

相关文章:

javascript - $broadcast 的问题

javascript - 子菜单在用户单击并在新页面中打开时保持事件状态

javascript - 如何将我自己的 jQuery 版本与浏览器化模块一起使用

javascript - 将 ruby​​ 插值嵌入到 html 字符串(变量)的 &lt;script&gt; 标签中?

c# - '$' 符号在 C# 6.0 中有什么作用?

javascript - 在javascript中调用带有双参数()的函数

angular - ionic 4 在键盘上方显示页脚

python - non_field_errors : ["Expected a list of items but got type "dict".“]

Angular 6 - HttpClient - 捕获错误

c# - 我可以在 C# 6 中将多个语句放入一个内插字符串中吗?