【问题标题】:Angular add style tag into innerHTMLAngular将样式标签添加到innerHTML
【发布时间】:2018-10-15 10:26:47
【问题描述】:

我创建了一个 Angular 项目,我想在 html 中插入 style CSS,但我不希望插入的 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>

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

我很欣赏任何类型的解决方案。

【问题讨论】:

  • 听起来你想要的就是文档中描述的Component Styles
  • 它是否适用于静态样式?你能添加一个stackblitz吗?

标签: javascript css angular


【解决方案1】:

您需要使用 @angular/platform-browser 的 DomSanitizer 来清理 HTML。
查看文档:https://angular.io/api/platform-browser/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

【讨论】:

  • 感谢您的解决方案 :),但是此解决方案还会更改 HelloComponent 上的 H1 的颜色,当更新样式时,HelloComponent 上的 H1 不会更新,只有 AppComponent 的样式.谢谢:)
  • @merahputih 您要查找的内容非常简单。只需将和 id 或一个类放到要应用样式的父组件中。这不是什么魔法,样式标签将全局应用样式。我会更新我的答案,告诉你怎么做。