What is ng-template in Angular: Explanation and Example
ng-template in Angular is a way to define a chunk of HTML that is not rendered immediately but can be used later in the template. It acts like a container for HTML that Angular can insert or reuse dynamically when needed.How It Works
Think of ng-template as a hidden blueprint for HTML content. It does not show anything on the page by itself. Instead, Angular keeps it ready and inserts it into the page only when you tell it to. This is like having a recipe card that you keep in your kitchen but only use when you want to cook that dish.
This mechanism helps Angular manage parts of the UI that appear conditionally or multiple times without cluttering the page with unused HTML. It works behind the scenes to keep your app efficient and organized.
Example
This example shows how ng-template holds content that appears only when a button is clicked.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <button (click)="show = !show">Toggle Message</button> <ng-template [ngIf]="show"> <p>Hello from ng-template!</p> </ng-template> ` }) export class AppComponent { show = false; }
When to Use
Use ng-template when you want to define HTML that should not show immediately but only under certain conditions or multiple times. It is useful for:
- Conditional content that appears or hides based on user actions.
- Reusable templates inside structural directives like
*ngIfor*ngFor. - Creating custom templates for components like modals, dropdowns, or lists.
For example, if you want to show a loading spinner only while data loads, you can put the spinner inside an ng-template and display it only when needed.
Key Points
ng-templatecontent is not rendered until explicitly used.- It helps keep templates clean and efficient by delaying rendering.
- Works well with Angular directives like
ngIfandngFor. - Acts as a reusable block of HTML for dynamic UI.
Key Takeaways
ng-template defines HTML that Angular renders only when needed.ngIf to control when content appears.