In Angular, building dynamic and reusable templates is a core feature, and the ng-template
directive plays a central role in this functionality. Unlike regular HTML elements, ng-template
is not rendered as a part of the DOM directly. Instead, it is used as a placeholder for rendering template fragments conditionally or dynamically.
In this article, we will cover what ng-template
is, when and why you should use it, and provide practical examples to illustrate its utility in Angular applications.
What is ng-template
?
ng-template
is a structural directive in Angular that defines a template fragment that can be rendered conditionally or dynamically. It does not produce any output in the DOM by itself, but it serves as a blueprint for rendering content when needed.
The basic syntax for using ng-template
is:
htmlCopy code<ng-template #templateRef>
<!-- Template content here -->
</ng-template>
Here, ng-template
holds the template content, but it will not render until it is explicitly instantiated.
Why Use ng-template
?
The primary reasons for using ng-template
include:
- Conditional Rendering: When combined with structural directives like
*ngIf
,ng-template
allows for deferred rendering of template content. - Dynamic Template Rendering: It helps dynamically insert templates based on conditions, making the UI more flexible and responsive to changing states.
- Reusability: It promotes code reusability by allowing template fragments to be defined once and reused across different parts of the component or application.
- Efficiency: Since
ng-template
does not render immediately, it can improve performance by rendering content only when needed.
When to Use ng-template
- Handling Conditional Views
- Use
ng-template
when you want to render different templates based on conditions without modifying the DOM structure prematurely.
- Use
- Defining Reusable Template Fragments
- When building reusable components or managing multiple conditional views,
ng-template
can be used to define fragments that are used repeatedly.
- When building reusable components or managing multiple conditional views,
- Creating Dynamic Components
- Use
ng-template
when creating components dynamically or rendering template content based on data or user interactions.
- Use
- Using with Angular Directives
- It is useful when working with directives like
ngIf
,ngFor
, or Angular’sngTemplateOutlet
, which rely on template references to display content dynamically.
- It is useful when working with directives like
How to Use ng-template
: Examples
1. Basic Usage with *ngIf
The most common use case for ng-template
is with the *ngIf
directive, where it allows conditional rendering with an alternative template.
Example:
htmlCopy code<div *ngIf="isLoggedIn; else loggedOut">
<p>Welcome, user!</p>
</div>
<ng-template #loggedOut>
<p>Please log in.</p>
</ng-template>
In this example:
- The content inside the
<div>
is rendered ifisLoggedIn
istrue
. - If
isLoggedIn
isfalse
, theng-template
with the#loggedOut
reference is displayed. - The
ng-template
here serves as an alternative view for the*ngIf
condition.
2. Using ng-template
with ngFor
ng-template
can also be used to customize how lists are rendered with the *ngFor
directive.
Example:
htmlCopy code<ng-template #itemTemplate let-item>
<div class="item">{{ item.name }}</div>
</ng-template>
<ng-container *ngFor="let item of items">
<ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }"></ng-container>
</ng-container>
In this example:
- The
ng-template
defines a reusable template fragment for rendering each item in the list. - The
*ngTemplateOutlet
directive is used to render theitemTemplate
for each item, with the context specifying the data to be passed into the template.
3. Dynamic Template Rendering with ngTemplateOutlet
Angular’s ngTemplateOutlet
directive allows rendering ng-template
dynamically, making it possible to switch between different templates based on component logic.
Example:
In the component:
typescriptCopy codeimport { Component } from '@angular/core';
@Component({
selector: 'app-dynamic-template',
templateUrl: './dynamic-template.component.html',
})
export class DynamicTemplateComponent {
isAdmin = true;
}
In the template:
htmlCopy code<ng-template #adminTemplate>
<p>Welcome, Admin!</p>
</ng-template>
<ng-template #userTemplate>
<p>Welcome, User!</p>
</ng-template>
<div [ngTemplateOutlet]="isAdmin ? adminTemplate : userTemplate"></div>
Here:
- Two templates (
adminTemplate
anduserTemplate
) are defined usingng-template
. - The
ngTemplateOutlet
directive dynamically renders one of the templates based on theisAdmin
variable. - This approach allows you to toggle between different templates without modifying the DOM directly.
4. Passing Context to ng-template
You can pass data to ng-template
using the context
object, which makes the template more dynamic and adaptable.
Example:
In the template:
htmlCopy code<ng-template #greetingTemplate let-name="name">
<p>Hello, {{ name }}!</p>
</ng-template>
<div *ngTemplateOutlet="greetingTemplate; context: { name: 'Alice' }"></div>
<div *ngTemplateOutlet="greetingTemplate; context: { name: 'Bob' }"></div>
In this example:
- The
greetingTemplate
accepts a variable namedname
using thelet-name
syntax. - The
ngTemplateOutlet
renders the template with different names by passing context objects. - This approach is useful when rendering template content that depends on dynamic data.
5. Using ng-template
in Custom Components
You can also use ng-template
to define custom template content that can be projected into components.
Example:
In a child component (custom-card.component.ts
):
typescriptCopy codeimport { Component, Input, TemplateRef } from '@angular/core';
@Component({
selector: 'app-custom-card',
template: `
<div class="card">
<ng-template [ngTemplateOutlet]="template"></ng-template>
</div>
`
})
export class CustomCardComponent {
@Input() template: TemplateRef<any>;
}
In the parent component’s template:
htmlCopy code<app-custom-card [template]="cardContent"></app-custom-card>
<ng-template #cardContent>
<h2>Custom Card Title</h2>
<p>This is some custom content inside the card.</p>
</ng-template>
In this example:
- The
ng-template
is used to define the content for a custom component (app-custom-card
). - The
ngTemplateOutlet
renders the projected content inside the component. - This approach enables dynamic template projection, enhancing reusability and flexibility.
Advanced Use Case: Dynamic Template Switching
Consider a more complex scenario where different templates need to be rendered based on user input or data changes.
In the component:
typescriptCopy codeimport { Component } from '@angular/core';
@Component({
selector: 'app-dynamic-content',
templateUrl: './dynamic-content.component.html',
})
export class DynamicContentComponent {
currentTemplate: 'template1' | 'template2' = 'template1';
toggleTemplate() {
this.currentTemplate = this.currentTemplate === 'template1' ? 'template2' : 'template1';
}
}
In the template:
htmlCopy code<button (click)="toggleTemplate()">Toggle Template</button>
<ng-template #template1>
<p>This is Template 1</p>
</ng-template>
<ng-template #template2>
<p>This is Template 2</p>
</ng-template>
<div [ngTemplateOutlet]="currentTemplate === 'template1' ? template1 : template2"></div>
Here:
- Two templates (
template1
andtemplate2
) are defined, and thengTemplateOutlet
directive dynamically switches between them. - The
toggleTemplate()
function toggles the current template, demonstrating howng-template
can be used to switch content based on user actions.
Conclusion
ng-template
is a powerful directive in Angular that enables flexible, efficient, and reusable template management. It provides a way to handle conditional rendering, dynamic template switching, and template projection without adding extra nodes to the DOM.
When to use ng-template
:
- For defining template fragments that need to be rendered conditionally or dynamically.
- For creating reusable templates in components.
- For managing complex template logic while maintaining clean and efficient markup.
By mastering ng-template
, you can build more dynamic, maintainable, and flexible Angular applications, taking full advantage of Angular’s structural directives and dynamic rendering capabilities.
4o