首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular2 innerHtml绑定删除样式属性

Angular2 innerHtml绑定删除样式属性
EN

Stack Overflow用户
提问于 2016-09-22 07:27:30
回答 1查看 66.4K关注 0票数 78

我的问题是,当我使用innererHtml binding - 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

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2016-12-15 19:44:41

通过完成所需的导入,我对yurzui的示例进行了一些改进:

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);
  }
}

我还必须在我的app.module.ts文件中添加类

import ...
import {SafeHtmlPipe} from "./pipes/safehtml.pipe";
@NgModule({
    declarations: [
        AppComponent,
        ...,
        SafeHtmlPipe  <--
    ],
    imports: [...],
    providers: [...],
    bootstrap: [AppComponent]
})
export class AppModule {
}
票数 49
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39628007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档