The ultimate guide to style content projection in Angular
Explore all possible approaches to style projected content as well as their advantages and downsides.
--
ng-content
is an important concept to create reusable and flexible components. With the help of ng-content
content can be projected by a parent component into a predefined slot. In some cases, you want to apply some styles to the projected content.
It doesn’t sound too hard. Does it? Well, it’s actually not so easy! Hence this blogpost 😉
We are not talking about adding the possibility to style our component, but about styling the projected content. If you are interested in the first please check out my other blogpost on how to create reusable components.
An example, please!
Let’s take a look at a practical use case. Imagine we want to implement a my-header
component that provides a projection slot and could also display a logo on the right side.
For our article, the projection slot is exciting. Especially the styles we want to apply to the projected content. Therefore we simplified the styles section in the components code below.
To ensure that the projected content is nicely placed, we use the > *
selector to apply a left margin to everything projected. Note that the projection slot is generic. This means it accepts any Angular component, Web component, or native element. Anything can be projected!
Imagine we project a native element in the form of an anchor tag, a button
and even a my-foo
component.