Angular content projection

Ravi Teja
Ravi Teja
May 14, 2019 · 1 min read

What is content projection?

Sometimes it’s not enough to just design a component and have a fixed view provided in the component’s template.

For example, let’s take a card component that prints the provided data as a fancy card.

One way to create such a component is to get the title, body and footer as component inputs via @Input

and the template (using Bootstrap for styling)

Sure, it does work fine, but what if we want to pass rich text which contains text decorations such as bold, italics, etc? That’s where content projection comes in.

Content projection using ng-content

The ng-content tag when used in a component's template projects the content provided during the component's usage

Whatever goes between the component’s tags will be projected as part of the component

The projected content could contain normal html elements and also other angular components.

After modifying our card component to use content projection, it can suddenly have images, colored text, etc.

Notice how HTML within <app-card> is being rendered as HTML instead of plain-text


Sometimes there is a requirement to project only specific elements, in that case projection selectors can be used.

These are the following selectors that could be used

Element selectors

Notice that although there are 2 buttons in the template, they don’t appear in the projected content

CSS Class selector

The data in the paragraph tags doesn’t appear in the projected content as we have used the CSS class selector “.content”

Attribute Selector

Will component’s styles apply to projected content?

No. Styles declared within a component will not be applied to the projected content unless the component’s ViewEncapsulation is set to Native or None.

Ravi Teja

Written by

Ravi Teja

Angular, Web, Java and other tech stuff

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade