In Angular, ng-content
, ng-template
, and ng-container
are all structural or content projection elements that help manage the rendering and composition of the DOM. Each serves a different purpose:
🔹 1. ng-content
✅ Use case: Content projection (used in Angular component design)
It allows you to project external content into a component’s template. Think of it as a placeholder where parent content will be inserted.
📌 Example:
<!-- parent.component.html -->
<app-child>
<p>This content will be projected</p>
</app-child>
<!-- child.component.html -->
<ng-content></ng-content>
🧠Key Points:
- Use in custom reusable components.
- Supports multiple slots using
select
:
<ng-content select="header"></ng-content>
<ng-content select="footer"></ng-content>
🔹 2. ng-template
✅ Use case: Define template fragments that are not rendered immediately but can be used later (conditionally or via *ngIf
, ngTemplateOutlet
, etc.).
📌 Example:
<ng-template #loading>
<p>Loading...</p>
</ng-template>
<div *ngIf="isLoading; else content">
<ng-container *ngTemplateOutlet="loading"></ng-container>
</div>
<ng-template #content>
<p>Data loaded!</p>
</ng-template>
🧠Key Points:
- Not part of the DOM until explicitly rendered.
- Useful in conditional rendering, ngIf else, or reusable templates.
🔹 3. ng-container
✅ Use case: A logical container without rendering any additional DOM element.
📌 Example:
<ng-container *ngIf="isAdmin">
<button>Edit</button>
<button>Delete</button>
</ng-container>
🧠Key Points:
- Does not render to DOM (i.e., no
<div>
or wrapper). - Useful for grouping structural directives (like
*ngIf
,*ngFor
) without introducing extra markup.
🧾 Summary Table:
Feature | ng-content | ng-template | ng-container |
---|---|---|---|
Purpose | Content projection | Define template fragments | Group DOM logically |
Renders HTML? | Yes (with projected content) | No (until explicitly used) | No |
DOM Element? | Yes (placeholder) | No | No |
Common Uses | Custom component design | *ngIf else , ngTemplateOutlet | Conditional rendering block |
Tags
Angular