Home > Article > Web Front-end > How to Style InnerHTML Content in Angular Using View Encapsulation?
Styling InnerHTML in Angular Using View Encapsulation
In Angular, setting the innerHTML property allows you to dynamically render HTML content within a component's view. However, you might encounter issues when trying to style this injected content.
Problem: When using innerHTML to inject HTML content that includes inline styles, the styles may not be applied. For instance, the following code will not apply the background-color style to the injected div element:
<code class="typescript">this.someHtmlCode = '<div style="background-color: blue;"><b>This is my HTML.</b></div>';</code>
Solution: Angular employs a concept called "emulated" view encapsulation by default. This prevents styles defined within components from interfering with styles defined outside of them. To allow inline styles for injected content, you need to change the encapsulation to None.
<code class="typescript">@Component({ selector: 'example', styles: ['.demo {background-color: blue}'], template: '<div [innerHTML]="someHtmlCode"></div>', encapsulation: ViewEncapsulation.None, })</code>
By setting the encapsulation property to None, Angular will no longer prevent inline styles from being applied. This allows you to define styles both within the component's styles array and in the injected HTML content, and Angular will automatically apply them to the DOM.
The above is the detailed content of How to Style InnerHTML Content in Angular Using View Encapsulation?. For more information, please follow other related articles on the PHP Chinese website!