Style doesn't work for innerhtml in Angular 2 Typescript

I am passing html as innerHtml to my view. Below is my opinion

<div [innerHTML]="someHtmlCode"></div>

      

if i pass the below code it works fine.

this.someHtmlCode = "<div><b>This is my HTML.</b></div>"

      

if i pass the below code which contains color it doesn't work.

 this.someHtmlCode = '<div style="background-color: blue;"><b>This is my HTML.</b></div>';

      

+3


source to share


3 answers


The behavior you receive is normal. The class added to innerHTML

is ignored because the default is encapsulation Emulated

. This means that Angular prevents styles from being intercepted inside and outside the component. You have to change encapsulation to None

in your component. This way, you can define classes wherever you want: inside styles

or in a separate stylesheet .css

, .scss

or .less

(it doesn't matter) and Angular will add them to the DOM automatically.



@Component({
  selector: 'example',
  styles: ['.demo {background-color: blue}'],
  template: '<div [innerHTML]="someHtmlCode"></div>',
  encapsulation: ViewEncapsulation.None,
})
export class Example {

  private someHtmlCode = '';

  constructor() {
    this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>';
  }

}

      

+13


source


I also faced the same problem but after reading this below link I figured out the solution and it was done without using pipes

Hope this helps you.



https://netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90

+2


source


Instead of inline style, I put style into a class.

Not sure if using the parameter class

is an option for you or not, but here's a demo of Plunker .

HTML:

this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>'

CSS

.demo{ background-color: blue; }

0


source







All Articles