Angular2渲染包含插值的清理字符串

时间:2017-11-13 20:11:17

标签: angular angular-template

我使用以下字符串
"Today's product of the day is {{product_code}} !"

上面的这个字符串,我已经清理并绕过了安全受信任的HTML this.DomSanitizer.bypassSecurityTrustHtml(str)
 并使用[innerHTML]放入我的模板 但是,此字符串还包含插值{{product_code}},应使用其实际值进行评估和渲染,以使输出必须为

  

"今天的产品是XYZ-52-TV!"

然而,这不会发生,而是使用插值的双花括号和变量名称来渲染字符串。

我该如何解决这个问题?

更新

组件模板:

<span [innerHTML]="trustHTML(str)"></span>

trustHTML()的代码:

  trustHTML(t){
    return this.DomSanitizer.bypassSecurityTrustHtml(t);
  }

str的价值:
"Today's product of the day is {{trustHTML(product_code)}} !"
使用此值出现的输出是(不需要的输出):
Today's product of the day is {{trustHTML(product_code)}} !

我也尝试了str的价值:
"Today's product of the day is <span [innerHTML]="trustHTML(product_code)"></span> !"
"Today's product of the day is product_code !"

1 个答案:

答案 0 :(得分:1)

DomSanitizer#bypassSecurityTrustHtml旨在从组件中调用。

了解这一点,并且知道您可以从调用该消毒剂的任何地方访问该完整字符串,只需从该函数返回完整构建的字符串,àla

{{ sanitizeProductLink(productId) }}

本身返回完整的字符串"Today's product of the day is XYZ-52-TV !"

另外,模糊假设:

但是,问题是,为什么要将[innerHTML]中的普通字符串注入其中。我假设您从上下文构建了一些类型的链接,更简洁的方法是创建一个静态模板并传入变量,例如

<span>Today's special is <a [link]="['special', product.id]">{{ product.name }}!</a></span>

或某些此类实施。

相关问题