簡體   English   中英

Angular將樣式標記添加到innerHTML中

[英]Angular add style tag into innerHTML

我創建了一個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>

編輯:我已經更新了我的問題,讓它更清楚:)

我很欣賞任何解決方案。

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

在您的特定情況下,您需要使用bypassSecurityTrustHtml()方法。 此外,僅將樣式應用於一個組件,請將id添加到目標組件並在樣式中使用它。 (如果該組件在Web中出現多次,則可以使用該類)。

例:

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 = ssc%2Fapp% 2Fapp.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM