DEV Community

karanam raghuvardhan
karanam raghuvardhan

Posted on

Content projection in Angular

In Angular, we often pass information from the parent to child components. The most straightforward way to do this is to use the @Input() decorator.

However, this decorator can only be used for passing the data. What happens if we want to pass the HTML or render the content dynamically? This is where the content projection comes into the picture.

What is Content Projection?

Content projection is a way of passing the HTML content from parent to child component. In Angular, this is achieved using the tag <ng-content></ng-content>.

ng-content acts as a placeholder in the child component template where the projected content is replaced.

A couple of things to remember while using the ng-content.

  • DOM will ignore the ng-content tag and it is never rendered
  • Any custom attributes applied to ng-content are ignored and do not apply to the HTML elements

Types of Content Projection

In this article, we will mainly discuss two types of content projection along with their use cases.

  1. Single Slot Content Projection
  2. Multi Slot Content Projection

Single Slot content projection

It is the most basic form of content projection in angular. Here, the child component contains only one slot onto which the parent can project its content.

In the example, we create a child component that uses <ng-content> as the placeholder for the parent.

Single slot content projection

Now we will use the above-created component in the parent component to project content in the child component

Single slot content projection in Parent

This will render the <p> tag inside the child component as we can see from the below result

Single slot content projection result

Multi Slot Content Projection

As the name suggests, this is a type of projection where the child will have multiple slots to render the projected content.

In this type, the child will have multiple slots with ng-content along with a CSS Select attribute. This selector will be used by the parent as an attribute to indicate the position.

Multi slot content projection

In the child component, if any of the ng-content tags don't have the selector, then all the projected content in the parent component without matching content will be projected.

Multi slot content projection in parent

This will render the <p> tag inside the child component as we can see from the below result and also the <p title> will be projected at the inside ng-content with the select attribute.

Multi slot content projection result

You can find the source code for this article here

Hope you enjoyed reading this article as much as enjoyed writing it.

Top comments (0)