ngTemplateOutlet
⭐ What is ngTemplateOutlet?
ngTemplateOutlet is an Angular directive that allows you to insert (render) an <ng-template> dynamically wherever you want.
It helps you:
✔ Reuse templates
✔ Show templates conditionally
✔ Pass context data into templates
✔ Build flexible UI structures
🧩 Basic Structure
First, define a template:
Now render it using ngTemplateOutlet:
Output:
👉 This is my template content!
🔍 How It Works
-
<ng-template>= Stored HTML block -
ngTemplateOutlet= Loads that template into the DOM
Angular does not display <ng-template> directly; it must be rendered using ngTemplateOutlet.
⭐ Example 1: Reusing a Template Multiple Times
Same template is used twice → Useful for DRY (Don’t Repeat Yourself).
⭐ Example 2: Passing Data (Context) to Template
Your template:
Use with context:
Output:
👉 User Name: Sanjit
⭐ Example 3: ngIf + ngTemplateOutlet (Dynamic UI)
If isOk = true → success template
If isOk = false → error template
⭐ Example 4: Rendering Different Templates in a Loop
⭐ Understanding Context Binding
Inside <ng-template> you can expose variables using:
⭐ Example 5: Using $implicit
$implicit is the default value passed to a template context.
Template:
Using $implicit:
Output:
👉 Hello Rahul!
🎯 Summary
| Feature | Description |
|---|---|
ngTemplateOutlet |
Renders an <ng-template> |
| Context | Allows passing data into template |
$implicit |
Default value inside template |
| Dynamic UI | Helpful for conditional rendering & reuse |
🧠 One-Line Summary
👉 ngTemplateOutlet lets you load reusable templates dynamically, optionally with data/context.
