【问题标题】:Inline styling in Angular2Angular2中的内联样式
【发布时间】:2017-07-31 12:26:42
【问题描述】:

我从 HTTP 调用中获取 HTML 代码块,其中 具有内联样式。我将 HTML 块放在一个变量中,并使用 [innerHTML] 将其插入我的页面,但我看不到插入的 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>";
  }
}

在上面的例子中,1234 没有变红。

这里是plnkr

【问题讨论】:

  • 请将代码添加到您的问题中,以展示您要完成的工作、尝试的内容以及失败的地方。也许是一个允许复制的 Plunker?
  • @GünterZöchbauer in stackoverflow.com/questions/36265026/… 查看您的第一条评论(在组件内)
  • 我让你创建一个问题而不是评论,因为在这里你可以添加代码;-)
  • @GünterZöchbauer 我现在添加了 plnkr

标签: angular


【解决方案1】:
  constructor(private sanitizer:DomSanitizer) {
    this.html = sanitizer.bypassSecurityTrustHtml("<span style=\"color:red;\">1234</span>");

Plunker example

另见

【讨论】:

    【解决方案2】:

    在 plunker 中更改您的代码,如下所示:

    import {Component, NgModule,ElementRef,ViewChild} from '@angular/core'
    
    @Component({
      selector: 'my-app',
      template: `
        <input type="text" [(ngModel)]="html">
        <div [innerHtml]="html" #value>
        </div>
      `,
    })
    export class App {
      name:string;
      html: string;
    
      @ViewChild("value") el : ElementRef
    
      constructor() {
        this.name = 'Angular2'
        this.html = "1234";
      }
      ngOnInit(){
        this.el.nativeElement.style.color = "red";
      }
    }
    

    【讨论】:

    • 我不会接受这个解决方案,因为 this.html 可能是一个页面的 HTML 代码,它有 1000 个 div 并且每个 div 都可以有内联 css。在这种情况下,此解决方案将不起作用。
    • 不要直接接触nativeElement,使用Renderer2
    猜你喜欢
    • 2016-09-21
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多