Creating components with Angular is a bless. The API to declare inputs and outputs is clear and simple. View encapsulation makes sure that styles don't leak outside of the component's host. However, there is one thing that is not clearly defined by the Angular framework: providing an API to let consumers customize styles of a component.
You can of course achieve it by setting up inputs. You would have to declare the inputs and put inline styles on elements inside your component. You would also sometimes have to use
@HostBinding to attach styles to the host element.
The alternative I suggest in this post is making use of CSS custom properties, also called variables. If you don't know what they are, there is a great page about this topic on MDN's website.
Let's directly have a look at an example of a card component. It has a title and projects content right below it.
The last CSS file is where we enable CSS customization. The card component uses a few CSS variables
--card-title-color. You can also note that we provide fallback values with the syntax:
color: var(--card-title-color, black /* <- fallback value */ );.
Let's now have a look at how one can consume the card component and customize its style.
Our application template declares two cards. Each receives a CSS class. In the CSS file, we say that the
--card-box-shadow of the cards should be
0 0 4px 0px grey.
.card-1gets a red title and
.card-2a blue one.
CSS variables, or custom properties, act like other CSS properties: inheritance and specificity rules apply the same way.
You can also define CSS variables for the whole application by using the
This technique enables developers and consumers to keep concerns separate: what is relevant to styling stays in CSS. It is also an elegant way for library creators to give more customization capabilities to their components.