Problem Statement:
When passing HTML code as innerHTML to a view, styles defined within the code are not being applied. If the HTML code does not include any inline styles, it displays correctly. However, when inline styles, such as background-color, are added to the HTML code, they are ignored.
Root Cause:
This behavior is a result of Angular's default component encapsulation being set to "Emulated." Emulated encapsulation prevents CSS styles from influencing elements both inside and outside of the component.
Solution:
To allow styles defined within innerHTML to be applied, the component's encapsulation must be changed to "None." This can be achieved by adding the following additional code to the app:
import { Component, ViewEncapsulation } from '@angular/core'; @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>'; } }
With encapsulation set to "None," styles defined within innerHTML will be added to the DOM automatically, allowing them to be applied to the elements created by the HTML code.
The above is the detailed content of Why Are Styles Not Applied to InnerHTML in Angular?. For more information, please follow other related articles on the PHP Chinese website!