Angular将样式标记添加到innerHTML中

时间:2018-05-04 21:31:01

标签: javascript css angular

我创建了一个Angular项目,我希望将style CSS插入到html中,但我不希望插入的CSS替换其他具有相同标记或类名的样式。

const testStyle = '<style>
  body {color: red}
  table {width : 200px}
  h1{font-size:12px}
  .another-same-class-name{color: blue;font-size: 13px}
</style>'

以上是我想要插入到我的组件模板中的样本样式

我的组件

@Component({

   selector : 'app-my-component',
   templateUrl: './my-template.component.html',
   styleUrls: ['./my-style.component.scss'],

})

export class MyComponent{

  myStyle:string

  ...

  ngOnInit(){
    const testStyle = '<style>
                         body {color: red}
                         table {width : 200px}
                         h1{font-size:12px}
                        .another-same-class-name{color: blue;font-size: 13px}
                      </style>'

    this.myStyle = testStyle

  }


  updateCss(newCss){
    this.myStyle = `<style>${newCss}</style>`
  }


}


<div #styleWillGoHere [innerHtml]="myStyle"></div>

编辑:我已更新我的问题,以使其更清晰:)

我感谢任何解决方案。

1 个答案:

答案 0 :(得分:3)

您需要使用CurrentApp.LicenseInformation.IsTrial的DomSanitizer来清理HTML。
看一下文档:https://angular.io/api/platform-browser/DomSanitizer

在您的特定情况下,您需要使用@angular/platform-browser方法。此外,仅将样式应用于一个组件,请将bypassSecurityTrustHtml()添加到目标组件并在样式中使用它。 (如果该组件在您的网络中出现多次,您可以使用该课程。)

示例:

id

DEMO: https://stackblitz.com/edit/angular-3kza7c?file=src%2Fapp%2Fapp.component.ts