本文介绍了Angular2 innerHtml 绑定删除样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题,当我使用 innererHtml 绑定时 - angular2 删除所有样式属性.这对我很重要,因为在我的任务中 - html 是在服务器端生成的,具有所有样式.示例:

@Component({选择器:'我的应用',模板:`<input type="text" [(ngModel)]="html"><div [innerHtml]="html">

`,})出口类应用{名称:字符串;html:字符串;构造函数(){this.name = 'Angular2'this.html = "<span style="color:red;">1234</span>";}}

但是在 DOM 中我只看到 1234 并且这个文本不是红色的.

http://plnkr.co/edit/UQJOFMKl9OwMRIJ38U8D?p=preview

谢谢!

解决方案

您可以利用 DomSanitized 来避免它.

最简单的方法是创建自定义管道,如:

import { DomSanitizer } from '@angular/platform-b​​rowser'import { PipeTransform, Pipe } from "@angular/core";@Pipe({ 名称:'safeHtml'})导出类 SafeHtmlPipe 实现 PipeTransform {构造函数(私有消毒:DomSanitizer){}变换(值){返回 this.sanitized.bypassSecurityTrustHtml(value);}}

所以你可以像这样使用它:

<div [innerHtml]="html | safeHtml"></div>

Plunker 示例

My problem, that when I use innererHtml binding - angular2 remove all styles attributes. It's important for me, bacause in my task - html is generated on server-side with all styles.Example:

@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>";
  }
}

But in DOM I see only 1234 and this text is not red.

http://plnkr.co/edit/UQJOFMKl9OwMRIJ38U8D?p=preview

Thank you!

解决方案

You can leverage DomSanitized to avoid it.

The easiest way is to create custom pipe like:

import { DomSanitizer } from '@angular/platform-browser'
import { PipeTransform, Pipe } from "@angular/core";

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

So you can use it like:

<div [innerHtml]="html | safeHtml"></div>

Plunker Example

这篇关于Angular2 innerHtml 绑定删除样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:35