If you are still using ng-deep to style child components you really should consider the alternatives.
Host styling, content projection, and CSS variables are all potential solutions for this common problem.
Let’s explore the options below 👇
#Angular
First a couple of words why we need ng-deep in the first place.
In Angular, component's styles are encapsulated within the component's element so that they don't affect the rest of the application.
That has a side effect of making it difficult to style child components.
To alleviate this issue, Angular provides an ng-deep selector which pierces the encapsulation of the child component.
All is good then?
Not really, the selector has been deprecated for years and is not recommended by the official docs.
:host selector may be used to create styles that target the component element itself, as opposed to targeting elements inside its template.
Host styles can be overridden from the parent component without the use of ng-deep.
Sometimes rearranging HTML slightly is all you need
Building on that example, content projection is another way to work around the view encapsulation issue.
See how in the example below, refactoring the <app-button-group> to use content projection gives us a way to style the host element of <app-button>?
In more complex scenarios, styling host might not be enough.
If you need more flexibility, exposing your component styles as CSS variables should be the go-to solution.
CSS vars are not affected by style encapsulation so they allow for styling across component boundaries.
Also, If you’re worried about the browser support, there is really no need to.
At the day of posting this, the support for CSS vars sits comfortably at 96.5%.
And IE11 is dead anyway (not supported by Angular 13+).
Lastly, since Angular 9, you can bind to CSS variables in the templates of your components by using the [style] binding.
What’s not to love? 😍
And that’s a wrap for the styles tip ✅
If you like the content, consider following @realTomaszKula on Twitter.
I’ll post more tips similar to this one from time to time 🅰️
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.