Angular View Encapsulation
As a beginner in Angular you ask yourself many questions. One of them is about view encapsulation: should you enable it or not? What exactly does it do? In this post, we share our experience and explain the difference in a short and understandable way.
View Encapsulation - What is it anyway?
When you turn on View Encapsulation, Angular skillfully isolates the styles of your components. Each style gets its own unique tag and remains strictly tied to its component.
<!-- Compiled HTML in the app -->
<div class="_ngcontent-c0 my-style">
This is my component
</div>
<style>
.my-style._ngcontent-c0 {
color: blue;
}
</style>
The beauty of this? You can use generic classes within your component without fear of collisions. No more long, unwieldy class names. But, as with everything, there's a catch: features like content reflection are left out. If you use a component part somewhere else, it loses its style. And beware: sometimes you can find yourself repeating styles, which can lead to inconsistency as well as more code.
Our two cents on this
Without tools like Tailwind CSS or similar and using View Encapsulation, styling can become a challenge. With View Encapsulation, you have to decide exactly which styles to assign directly to components and which to leave global to avoid inconsistency and duplicate code. However, if you use Tailwind CSS, much is made easier. Most styles are global anyway, and you can reserve the component-specific styles for really unique requirements that you don't want to be global. Even if you have the option to use ::ng-deep, this should be avoided. Styles defined with ::ng-deep should be considered global and not inserted into the component stylesheet when using view encapsulation.
Conclusion
There is no black or white. It all depends on the organization of your styling approach. Us? We rely on Encapsulation and mostly resort to Tailwind - for obvious reasons.