The ultimate guide on how to create customizable Angular components
best practices, anti-patterns, ng-deep, global styles, mixins, CSS vars, and CSS part, all covered in one article!
Angular is inspired by the core concepts of web components. Therefore it uses components and the core ideas of Shadow DOM.
For historical reasons, by default, Angular provides its own implementation of Shadow DOM. However, we can still use the
encapsulation property on the components class decorator to switch to native Shadow DOM or even disable encapsulation completely.
Whenever we implement or use a component with native Shadow DOM or emulated Shadow DOM, we should always consider the style of our components as private.
Think of styles in the same way as code. Would you try to overwrite a components TypeScript code? Probably not!
But, wait! We often need to apply different styles to components based on use cases. How can we do that without overwriting the styles?
Practical use case
Imagine we have a simple chips component that allows us to select and deselect a chip.
The code and styles for such a component could look like this.
This component seems great. However, the colors do not represent our brand. So we want to use this component, but we need to change the colors!
Bad practice — What you should avoid!
Well, we can go ahead and try to update the
.chips-container background by adding the following code to our global styles (
The equivalent of updating the global styles would be to update our app components style or, well, basically any components styles with a selector that uses
ng-deepdisables encapsulations for a style…