ViewEncapsulation Emulated and override css from a component in Angular
This article will be to clarify how to override a css from an Angular component coming from a 3rd party library as PrimeNG, AngularMaterial or other libararies that in some cases don’t expose a way to do.
Let’s analyse an example:
In this image:
- the `test.component` is inside the `hello.component` and has an attribute `_ngcontent-c1`
- the div inside test component has an attribute `_ngcontent-c2`
The selector generated for the element with the class or-PP(green line in image)
is using a class selector combined with an attribute that makes it strong (that’s how angular emulates the shadow dom — css specificity).
Also if you declare a class or-PP
in the parent of `test.component` (hello.component) it will not use the test component attribute `_ngcontent-c2` but the parent one `_ngcontent-c1` and this is why any class declared in the parent can’t affect anything inside a child component.
So this `test.component` could be a 3rd party component where we want to apply a css change for some elements inside.
So what to do?
- ::ng-deep
this solution is deprecated and should not be used anymore. - open a Pull Request in the 3rd party library to expose a style input for the target component to go override the css at the right spot.
- (most used probably) create a global class that override the element style but don’t forget to add the !IMPORTANT.
Example: `color: yellow !important;`
Bonus: You can make solution 3 specific per view (context), you have to add a wrapper class in the path of your target component then globally use it to wrap the real class or css selector you want to override.
You can find a draft of a live demo here
Keep up with our content by following us @FrontEndTricks & don’t forget to give it some 👏👏👏.
~ Thank you ~