merahputih
merahputih

Reputation: 115

Angular add style tag into innerHTML

I create an Angular project and I wanted to insert style CSS into the html, but I don't want the inserted CSS replace other style that have the same tag or class name.

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

Above is my sample style that I want to insert into my component template

My Component

@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>

Edit: I have update my question, to make it more clear :)

I appreciate any kind of solution.

Upvotes: 9

Views: 17156

Answers (2)

you can use DomSanitizer bypassSecurityTrustHtml

Upvotes: -1

The.Bear
The.Bear

Reputation: 5855

You need to use DomSanitizer of @angular/platform-browser to sanitize the HTML.
Take a look of the docs: https://angular.io/api/platform-browser/DomSanitizer.

In your particular case, you need to use bypassSecurityTrustHtml() method. Also, for apply styles only to one component, add an id to your target component and use it in your styles. (You can use class if that component will appear more than once in your web).

EXAMPLE:

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>`);
  }
}

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

Upvotes: 17

Related Questions