Why Isn't CSS Applied to InnerHTML Content in Angular?
In Angular, injecting HTML content into a view using the innerHTML property poses a problem: styling may not be applied as expected. This is due to Angular's encapsulation mechanism, which prevents external styles from interfering with content within a component.
Understanding Shadow DOM Encapsulation
By default, Angular uses Emulated encapsulation, creating a shadow DOM and isolating component styles. Therefore, styles defined outside the component's scope, within the HTML injected by innerHTML, will be ignored.
Solution: Change Encapsulation to None
To resolve this issue, you can override Angular's encapsulation by setting encapsulation to None in your component. This will allow styles from external sources to be applied to the injected HTML content.
Here's an example:
<code class="typescript">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 { someHtmlCode = `<div class="demo"><b>This is my HTML.</b></div>`; }</code>
By setting encapsulation to None, we disable Angular's shadow DOM and allow CSS from within the injected HTML to take effect. As a result, the text within the injected HTML div will be rendered with a background color of blue.
The above is the detailed content of Why Doesn\'t My CSS Apply to InnerHTML Content in Angular?. For more information, please follow other related articles on the PHP Chinese website!