DEV Community

Benjamin Arambide
Benjamin Arambide

Posted on

How can you use Angular's `ng-template` beyond basic *ngIf or *ngFor?

Yes! Angular's ng-template combined with *ngTemplateOutlet allows you to define and render dynamic templates — acting like content "portals" or reusable layout blocks.

🔧 Example: Dynamic Template Switching

<ng-template #loadingTemplate>
  <div class="spinner">Loading...</div>
</ng-template>

<ng-container *ngTemplateOutlet="isLoading ? loadingTemplate : mainContent"></ng-container>

<ng-template #mainContent>
  <p>The data is loaded!</p>
</ng-template>

Enter fullscreen mode Exit fullscreen mode

🔍 What’s Happening?

  • You define named templates using #templateRef.
  • You dynamically insert a template using *ngTemplateOutlet.
  • This cleanly switches between content blocks without cluttering your HTML with logic.

🧠 Why It’s Useful

  • Keeps your templates clean and declarative.
  • Ideal for conditional UIs like modals, loading spinners, and card layouts.
  • Encourages reusable content logic, especially in component libraries.

🧩 Bonus: Passing Context

Templates can accept custom data too:

<ng-template #userCard let-user="user">
  <div>{{ user.name }}</div>
</ng-template>

<ng-container *ngTemplateOutlet="userCard; context: { user: currentUser }"></ng-container>

Enter fullscreen mode Exit fullscreen mode
  • let-user="user" allows access to context inside the template.
  • You can build flexible, data-driven UIs this way.

📌 Summary

  • ng-template + *ngTemplateOutlet = Angular’s hidden power feature.
  • Enables reusable, dynamic content structures.
  • Cleaner alternative to nested *ngIf, ideal for advanced UI patterns.

Use it to build smarter, more modular Angular components!

Top comments (0)