0
0
AngularConceptBeginner · 3 min read

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.

typescript
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;
}
Output
When the button is clicked, the text 'Hello from ng-template!' appears or disappears.
🎯

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 *ngIf or *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-template content is not rendered until explicitly used.
  • It helps keep templates clean and efficient by delaying rendering.
  • Works well with Angular directives like ngIf and ngFor.
  • Acts as a reusable block of HTML for dynamic UI.

Key Takeaways

ng-template defines HTML that Angular renders only when needed.
It helps manage conditional and reusable UI parts efficiently.
Use it with directives like ngIf to control when content appears.
It keeps your Angular templates clean and organized.