Angular 5:显示来自服务器响应的 html AND xml
Angular 5: Display html AND xml from server response
我有一个场景,我需要显示来自服务器发送的相同字符串的 html 和 xml。
服务器的回复如下所示:
This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.
我试过了:
text;
msg = 'This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.'
constructor(private domSanitizer: DomSanitizer) {
}
ngOnInit() {
this.text = this.getInnerHTMLValue();
}
getInnerHTMLValue() {
return this.domSanitizer.bypassSecurityTrustHtml(this.msg);
}
html:
<pre [innerText]="text"></pre>
我收到此错误:
SafeValue must use [property]=binding:...
当我使用 [innerHTML]
而不是 [innerText]
时,xml 已被清除。
如何显示示例 xml 代码以及解析 html 标签,例如 <b>
标签?
至少我怎样才能摆脱那个错误?
恐怕这不可能。看看 WC3 specs:
User agents must treat elements and attributes that they do not
understand as semantically neutral; leaving them in the DOM (for DOM
processors), and styling them according to CSS (for CSS processors),
but not inferring any meaning from them.
意思是,尽管您的浏览器不知道这些元素,但它们将是 dom 的一部分,因此不会显示在文本中。
您唯一的解决方案是编码除 <b>
、<i>
、...之外的所有标签:<note>
-> <note>
或使用 markdown 之类的东西格式化。
作为最简单的解决方法,只需使用 msg
而无需按原样进行消毒:
<pre>{{msg}}</pre>
因为它不会被解释,所以没有必要进行消毒。 (当然,像 <b>
这样的标签也不会被解释。)
我有一个场景,我需要显示来自服务器发送的相同字符串的 html 和 xml。
服务器的回复如下所示:
This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.
我试过了:
text;
msg = 'This is sample text with <b>bold text</b> and also some xml like this <note><to>you</to><from>me</from><heading>title</heading><body>message</body></note>. As you can see it contains both xml to display and html to render.'
constructor(private domSanitizer: DomSanitizer) {
}
ngOnInit() {
this.text = this.getInnerHTMLValue();
}
getInnerHTMLValue() {
return this.domSanitizer.bypassSecurityTrustHtml(this.msg);
}
html:
<pre [innerText]="text"></pre>
我收到此错误:
SafeValue must use [property]=binding:...
当我使用 [innerHTML]
而不是 [innerText]
时,xml 已被清除。
如何显示示例 xml 代码以及解析 html 标签,例如 <b>
标签?
至少我怎样才能摆脱那个错误?
恐怕这不可能。看看 WC3 specs:
User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them.
意思是,尽管您的浏览器不知道这些元素,但它们将是 dom 的一部分,因此不会显示在文本中。
您唯一的解决方案是编码除 <b>
、<i>
、...之外的所有标签:<note>
-> <note>
或使用 markdown 之类的东西格式化。
作为最简单的解决方法,只需使用 msg
而无需按原样进行消毒:
<pre>{{msg}}</pre>
因为它不会被解释,所以没有必要进行消毒。 (当然,像 <b>
这样的标签也不会被解释。)