ng-content vs ng-templatevs ng-container in angualr

 In Angular, ng-contentng-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 *ngIfngTemplateOutlet, 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 renderingngIf 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:

Featureng-contentng-templateng-container
PurposeContent projectionDefine template fragmentsGroup DOM logically
Renders HTML?Yes (with projected content)No (until explicitly used)No
DOM Element?Yes (placeholder)NoNo
Common UsesCustom component design*ngIf elsengTemplateOutletConditional rendering block

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form