我正在从远程服务器获取帖子的数据,帖子的数据包含带有 style
的 html和class
属性(从所见即所得编辑器生成)。
我想按原样呈现 html 数据,而不对其进行过滤或清理。
我尝试使用这个方法:
<div [innerHTML]="post.body"></div>
但是 Angular 正在删除 style
来自 html 的属性。
是否有办法保留 html 属性(即使它很危险)?
最佳答案
我认为你无论如何都必须这样做:
import { Component } from '@angular/core';
import { DomSanitizationService, SecurityContext, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="_htmlProperty"></div>
`
})
export class AppComponent {
_htmlProperty: string = 'AAA<input type="text" name="name">BBB';
constructor(private _sanitizer: DomSanitizationService){ }
public get htmlProperty() : SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this._htmlProperty);
}
}
您需要像 Angular 1 中那样清理 html。*
关于angularjs - 如何在 Angular 2 模板内显示获取的 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379253/