DEV Community

Cover image for Multi Slots in Angular?
Abimael Barea
Abimael Barea

Posted on

Multi Slots in Angular?

One exciting concept of Angular is:

Content Projection: pattern in which you insert, or project, the content you want to use inside another component

This concept exists as part of the HTML Standard and is known as:

Slot: placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.

Content Projection can be achieved with an Angular directive name as ng-content, and there are two main ways of doing it.


Simple

A component accepts content from a single source.

Component Definition

Let's load some additional content:

<ng-content></ng-content>
Enter fullscreen mode Exit fullscreen mode

Usage

<app-simple-content>
  <p>This is a test</p>
</app-simple-content>
Enter fullscreen mode Exit fullscreen mode

We can observe how the <p> is renderer as a child node of <app-simple-content> in the DOM Tree:

Image description


Multiple

A component accepts content from multiple sources.

Component Definition

<p>Let's load the main content:</p>
<ng-content select="[main]"></ng-content>
<p>Let's load some extra content:</p>
<ng-content select="[extra]"></ng-content>
<p>Let's load default content:</p>
<ng-content></ng-content>
Enter fullscreen mode Exit fullscreen mode

Usage with one

<app-multi-content>
  <span extra>EXTRA</span>
</app-multi-content>
Enter fullscreen mode Exit fullscreen mode

We can observe how the <span> is renderer as a child node of <app-multi-content> in the DOM Tree occupying the space for EXTRA:

Image description

Usage with all

<app-multi-content>
  <span main>MAIN</span>
  <span extra>EXTRA</span>
  <span>DEFAULT</span>
</app-multi-content>
Enter fullscreen mode Exit fullscreen mode

We can observe how the different <span> are renderer as a child node of <app-multi-content> in the DOM Tree occupying their own space:

Image description


Using Content Projection opens a door for applying the Composite Pattern:

Image description

The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies.


Full example

The detailed implementation is in one of my Github repos

Top comments (0)