Discover how to make your Angular components magically accept any content you want without rewriting them!
Why ng-content for slot-based composition in Angular? - Purpose & Use Cases
Imagine building a reusable card component where you want to place different content like a title, image, and footer manually each time by editing the component's internal template.
Manually changing the component's template for every variation is slow, error-prone, and makes your code hard to maintain and reuse.
Using ng-content with slots lets you define placeholders inside your component where you can insert any content from outside, making your component flexible and reusable without changing its code.
<card> <h1 class="title">Title</h1> <img class="image" src="image.jpg"> <footer class="footer">Footer text</footer> </card>
<ng-content select=".title"></ng-content> <ng-content select=".image"></ng-content> <ng-content select=".footer"></ng-content>
You can create versatile components that accept different content in specific places, making your UI flexible and easier to manage.
A modal dialog component where you can insert a custom header, body, and footer content from outside without rewriting the modal itself.
Manually editing component templates for each use is inefficient.
ng-content slots let you insert external content into components.
This makes components reusable, flexible, and easier to maintain.