::ng-deep alternatives
Explore alternate approaches to the deprecated::ng-deep Angular API to avoid legacy code and hard to debug side effects
--
Style encapsulation is one of many great Angular features. Style encapsulation ensures that component styles don’t leak out and affect the rest of the page.
Thx to encapsulation, only div
elements inside our component get a blue background. All others on the page don’t.
So we agree, encapsulation is great! But, in some use cases encapsulation also introduces some challenges. Let’s take a look.
Let’s imagine we want to customize the div
of the FooComponent
above. Instead of displaying a blue background, we want to show a green background. So we would try to overwrite the foo
components div
with a green
background.
Because of encapsulation, this approach does not work. We can not use a straight-forwarded CSS selector to style encapsulated components from the outside. It makes sense. They are encapsulated, right?!
Another case where encapsulation makes it harder to style things is content projection.
Imagine we have a bar
component that accepts the foo
component as content and wants to display the div again with a green background.
We target all divs and change their background to green. But again, our foo
component is nicely displayed, but it’s div
has a blue background, not a green one.
Again, this makes sense. That’s the whole idea of encapsulation. Does that mean that we can’t style encapsulated components? No. There are various ways to deal with this.