Angular Nested, Arbitrary Content Projection

Viewed 155

In Angular, is it possible to do something like

<my-component>
  <h1>Some text</h1>
  <p>Some text</p>
  ...
</my-component

and then in my-component have it turn into

<div class="container">
  <h1>Some text</h1>
</div>
<div class="container>
  <p>Some text</p>
</div>
...

where the number and types of elements to project is arbitrary? Each child element needs to be placed within a new <div class="container">, but the child elements could be any type and there is no set number of them.

2 Answers

This can be achieved by using the ng-content directive in the host component. So in your example the my-component markup should look like this <ng-content><ng-content>

This can be achieved easily using ng-content with Multi-slot content projection (Angular documentation):

<div class="container">
  <ng-content select="h1"></ng-content>
</div>
<div class="container">
  <ng-content select="p"></ng-content>
</div>
Related