Ida – Logo
Angular-View-Encapsulation-2.webp

Angular View Encapsulation

3 min

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.


More Posts

35.  Energy Efficiency in Software Architectures

With the increasing emphasis on sustainability and conserving energy, the realm of software architectures isn't left behind. Achieving energy efficiency in software design is now more critical than ever.

41.  Angular Standalone Components

Explore Angular Standalone Components. This article delves into creating and managing standalone components, showcasing how they simplify and modularize Angular development with practical code snippets.