这个问题在这里已有答案:
我的问题,当我使用innererHtml绑定时 - angular2删除所有样式属性 . 这对我来说很重要,因为在我的任务中 - html是在服务器端生成的,具有所有样式 . 例:
@Component({
selector: 'my-app',
template: `
<input type="text" [(ngModel)]="html">
<div [innerHtml]="html">
</div>
`,
})
export class App {
name:string;
html: string;
constructor() {
this.name = 'Angular2'
this.html = "<span style=\"color:red;\">1234</span>";
}
}
但是在DOM中我只看到了1234,而且这个文字并不是红色的 .
http://plnkr.co/edit/UQJOFMKl9OwMRIJ38U8D?p=preview
谢谢!
4 回答
Angular 2的目标是更多declarative approach,因此直接操纵HTML is often discouraged .
我相信(差不多)所有的HTML操作都会被修补,以便通过angular的DOM清理进行过滤 . 你可以想象
style
属性不是为span元素列入白名单,实际上,span has no allowed attributes目前 .您可以利用
DomSanitized
来避免它 .最简单的方法是创建自定义管道,如:
所以你可以使用它:
Plunker Example
请注意,
sanitizer
有一些信任内容的方法,例如通过https://stackoverflow.com/a/41089093/142714
因此,
bypassSecurityTrustStyle
也可能是您想要的,因为这将在您的HTML内容中显示内联样式(value
) .[1] docs:https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
我通过完成所需的导入改进了yurzui的例子:
我还必须在app.module.ts文件中添加该类