Angular2 呈现包含插值的经过清理的字符串
Angular2 render sanitised string containing interpolation
我正在使用以下字符串
"Today's product of the day is {{product_code}} !"
上面的这个字符串,我已经清理并绕过了安全信任 HTML
this.DomSanitizer.bypassSecurityTrustHtml(str)
并使用 [innerHTML]
.
放入我的模板
但是,此字符串还包含插值 {{product_code}}
,应该使用其实际值对其进行评估和渲染,因此输出必须是
"Today's product of the day is 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 !"
DomSanitizer#bypassSecurityTrustHtml
设计为从组件调用。
知道这一点,并且知道您可以从调用消毒剂的任何地方访问完整的字符串,只是 return 来自该函数的完全构建的字符串,à la
{{ sanitizeProductLink(productId) }}
它本身 return 是完整的字符串 "Today's product of the day is XYZ-52-TV !"
。
附加的,模糊的假设:
不过,这引出了一个问题,为什么要将纯字符串注入 [innerHTML]
以供使用。我从上下文假设你正在构建某种 link,一种更简洁的方法是制作一个静态模板并传入变量,比如
<span>Today's special is <a [link]="['special', product.id]">{{ product.name }}!</a></span>
或一些这样的实现。
我正在使用以下字符串
"Today's product of the day is {{product_code}} !"
上面的这个字符串,我已经清理并绕过了安全信任 HTML
this.DomSanitizer.bypassSecurityTrustHtml(str)
并使用 [innerHTML]
.
放入我的模板
但是,此字符串还包含插值 {{product_code}}
,应该使用其实际值对其进行评估和渲染,因此输出必须是
"Today's product of the day is 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 !"
DomSanitizer#bypassSecurityTrustHtml
设计为从组件调用。
知道这一点,并且知道您可以从调用消毒剂的任何地方访问完整的字符串,只是 return 来自该函数的完全构建的字符串,à la
{{ sanitizeProductLink(productId) }}
它本身 return 是完整的字符串 "Today's product of the day is XYZ-52-TV !"
。
附加的,模糊的假设:
不过,这引出了一个问题,为什么要将纯字符串注入 [innerHTML]
以供使用。我从上下文假设你正在构建某种 link,一种更简洁的方法是制作一个静态模板并传入变量,比如
<span>Today's special is <a [link]="['special', product.id]">{{ product.name }}!</a></span>
或一些这样的实现。