首页 > 解决方案 > Angular将样式标签添加到innerHTML

问题描述

我创建了一个 Angular 项目,我想将styleCSS 插入到 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>

编辑:我已经更新了我的问题,让它更清楚:)

我很欣赏任何一种解决方案。

标签: javascriptcssangular

解决方案


您需要使用 DomSanitizer@angular/platform-browser来清理 HTML。
查看文档:https ://angular.io/api/platform-b​​rowser/DomSanitizer 。

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

例子:

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `
      <div id="myId">
          <div [innerHtml]="myStyle"></div>
          <h1>Hello</h1>
      </div>
  `
})
export class AppComponent {
  myStyle: SafeHtml;

  constructor(private _sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.myStyle =
      this._sanitizer.bypassSecurityTrustHtml(`<style>#myId h1{color: red}</style>`);
  }
}

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


推荐阅读