【问题标题】:Angular 2 Adding html dynamically to DOM, style not working [duplicate]Angular 2将html动态添加到DOM,样式不起作用[重复]
【发布时间】:2018-02-25 00:53:43
【问题描述】:

您好,我正在尝试从 api 返回的文件中添加 html,这是有效的。我需要帮助的是,当我添加内联样式时它不起作用,但是如果我在 style.css 中创建一个类并将其添加到 html 中,它就会起作用。

所有这些都说,我需要让内联样式正常工作。我想让<span style="color:red;">I am red</span> 工作。

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="onClick()">Click To Add Html</button>
    </div>
    <div *ngIf="html!==''" [innerHtml]="html"></div>
  `,
})
export class App {
  name:string;
  html:string=null;

  const htmlConst:string = `<span style="color:red;">I am red</span>`;
  /*
  I have tried [style] = "color:red;"
  style="color:red;"
  */
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  onClick():void{
    if(this.html !== ''){
      this.html= this.htmlConst;
    }
    else{
      this.html = '';
    }
  }
}

任何建议都会有所帮助。

【问题讨论】:

    标签: css angular2-services


    【解决方案1】:
        import { Component,ViewEncapsulation } from '@angular/core';
    
        @Component({
          selector: 'my-app',
          template: `
            <div>
              <h2>Hello {{name}}</h2>
              <button (click)="onClick()">Click To Add Html</button>
            </div>
            <div *ngIf="html!==''" [innerHtml]="html"></div>
          `,
        encapsulation: ViewEncapsulation.None
        })
    

    请参考https://toddmotto.com/emulated-native-shadow-dom-angular-2-view-encapsulation

    【讨论】:

    • 您能否在此处添加一个关于它如何解决问题的解释,而不仅仅是一个参考链接?
    • 参考链接有详细解释。这个问题已经在堆栈溢出stackoverflow.com/questions/44210786/…中得到解答
    • 那么你应该标记为重复
    • 感谢您的参考,但这仍然不起作用。是的,这是一个非常相似的问题,但我想使用内联 css 而不是在所有不同的方式上更改 css 文件来使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2020-04-26
    • 2017-11-21
    • 1970-01-01
    • 2021-06-16
    • 2017-11-16
    相关资源
    最近更新 更多