Web服务以这种格式将数据返回到我的应用程序(遗憾的是我无法控制服务器输出):
<p> This is a paragraph </p>
尝试使用innerHtml
显示此数据时,结果如下
<p>This is a paragraph</p>
如何将格式传递给浏览器,以便解释段落标记并显示它?
Stackoverflow解释<p>
:
这是一个段落
用于演示https://plnkr.co/edit/BbAVrT8F1rJGZnJmov1g?p=preview的代码,下面还列出了代码。
@Component({
selector: 'my-app',
template: `
<div [innerHtml] = "name">
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `<p>This is a paragraph</p>`
}
}
我已尝试<script>decodeURI({{name}})</script>
,但只返回<"
。
我还查看了其他堆栈问题并尝试使用管道来绕过html的安全性,但是没有用。阅读Angular2文档听起来并不是它的目的。我也尝试了样式覆盖,它失败了,因为这不是一个样式,它是纯粹的html:
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value: string) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
答案 0 :(得分:2)
您首先需要解码这些实体引用,您可以让浏览器为您执行此操作,就像在下面的代码示例中一样。我们假设getData()
返回包含您数据的Observable
.
.
.
class SomeClass ... {
dataBoundProperty: string;
someFunction() {
this.dataService.getData()
.subscribe(dataStr => {
let dummyElem = document.createElement('DIV');
dummyElem.innerHTML = dataStr;
document.body.appendChild(dummyElem);
this.dataBoundProperty = dummyElem.textContent; // just grap the decoded string which contains the desired HTML tags
document.body.removeChild(dummyElem);
});
}
}
答案 1 :(得分:0)
我根据@ Dummy的帖子创建了这个功能。它在组件内部,并从html调用。
public void EThread()
{
HttpWebRequest HWRequest = (HttpWebRequest)WebRequest.Create(_AjaxURL);
HWRequest.Method = "POST";
HWRequest.ContentType = "text/xml; encoding='utf-8'";
string StrID;
while(!_RequiredIDs.IsEmpty)
if (_RequiredIDs.TryDequeue(out StrID))
{
Extract(StrID, ref HWRequest);
HWRequest.Reset();
}
}
调用html
export class SomeComponent {
public dummyElem = document.createElement('DIV');
...
decode(text: string): string {
var ret:string = "";
this.dummyElem.innerHTML = text;
document.body.appendChild(this.dummyElem);
ret = this.dummyElem.textContent; // just grap the decoded string which contains the desired HTML tags
document.body.removeChild(this.dummyElem);
return ret;
}
}
不“感觉”非常优雅或正确,但它有效。