How to Use Multi Slot Content Projection in Angular
In Angular, use
<ng-content select="[slot-name]"></ng-content> inside your component template to define multiple slots. Then, when using the component, wrap content with matching selectors like <div header> to project content into each slot.Syntax
Multi slot content projection uses multiple <ng-content> tags with select attributes to define named slots. The select attribute uses CSS selectors to match projected content.
In the parent component, wrap content with elements matching the selectors to project into each slot.
html
<!-- Child component template -->
<div>
<header>
<ng-content select="[header]"></ng-content>
</header>
<main>
<ng-content></ng-content> <!-- default slot -->
</main>
<footer>
<ng-content select="[footer]"></ng-content>
</footer>
</div>Example
This example shows a card component with three slots: header, default, and footer. The parent component projects content into each slot using attributes.
html
<!-- card.component.html --> <div class="card"> <div class="card-header"> <ng-content select="[header]"></ng-content> </div> <div class="card-body"> <ng-content></ng-content> </div> <div class="card-footer"> <ng-content select="[footer]"></ng-content> </div> </div> <!-- parent.component.html --> <app-card> <h1 header>Title goes here</h1> <p>This is the main content inside the card.</p> <button footer>Save</button> </app-card>
Output
<div class="card">
<div class="card-header">
<h1>Title goes here</h1>
</div>
<div class="card-body">
<p>This is the main content inside the card.</p>
</div>
<div class="card-footer">
<button>Save</button>
</div>
</div>
Common Pitfalls
- Not using matching selectors: The
selectattribute must match the attribute or element used in the parent content exactly. - Forgetting the default slot: Content without a matching selector goes into the
<ng-content>withoutselect. - Using invalid selectors: Only simple attribute or element selectors work; complex selectors may fail.
html
<!-- Wrong: selector does not match attribute --> <ng-content select="header"></ng-content> <!-- looks for <header> element, not [header] attribute --> <!-- Right: use attribute selector --> <ng-content select="[header]"></ng-content>
Quick Reference
- <ng-content>: Projects content into component.
- select="[attr]": Matches elements with attribute
attr. - Default slot:
<ng-content>withoutselect. - Parent content must use matching attributes or elements.
Key Takeaways
Use multiple
<ng-content select="[attr]"> tags to create named slots in Angular components.Match the
select attribute with attributes or elements in the parent content to project correctly.Content without a matching selector goes into the default
<ng-content> slot.Selectors must be simple attribute or element selectors; complex CSS selectors may not work.
Always test projection to ensure content appears in the intended slots.