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>';
source to share
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>';
}
}
source to share
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
source to share