Styling inner HTML with Angular special selectors

Styling inner HTML with Angular special selectors

In this post I show how to style the HTML in Angular’s [innerHtml] using special style selectors ::ng-deep and :host.

The problem

In an application I’m working, we’re using an open source text editor that saves text as HTML in the backend for certain product descriptions. To display the saved HTML we used the [innerHTML] directive, however, some of the styles saved to the backend did match the CSS theme on the front end, making for ugly looking typography. To fix this, I tried styling the HTML blocks as I normally would but to no avail! There must be another way to target the embedded HTML.

Inner HTML directive Angular

The solution

After some research and looking through the Angular styling documentation, I found that I was able to successfully target and style the HTML blocks inside of the [innerHtml] with the :host and ::ng-deep special style selectors.

Styling with Angular special selectors

I needed both the :host and ::ng-deep pseudo-selectors because I wanted to keep the scope of this style to the current component and all its descendants. If I just used ::ng-deep pseudo-selector without :host , then the style can bleed into other components.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.