0
0
Angularframework~3 mins

Why ng-content for slot-based composition in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your Angular components magically accept any content you want without rewriting them!

The Scenario

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.

The Problem

Manually changing the component's template for every variation is slow, error-prone, and makes your code hard to maintain and reuse.

The Solution

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.

Before vs After
Before
<card>
  <h1 class="title">Title</h1>
  <img class="image" src="image.jpg">
  <footer class="footer">Footer text</footer>
</card>
After
  <ng-content select=".title"></ng-content>
  <ng-content select=".image"></ng-content>
  <ng-content select=".footer"></ng-content>
What It Enables

You can create versatile components that accept different content in specific places, making your UI flexible and easier to manage.

Real Life Example

A modal dialog component where you can insert a custom header, body, and footer content from outside without rewriting the modal itself.

Key Takeaways

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.