Angular

ng-template in Angular: Angular templates

Angular template ng-template

In Angular, the ng-template directive is a powerful tool that allows developers to create dynamic, reusable, and conditional templates. Unlike regular HTML tags, ng-template is Angular-specific and isn’t rendered in the DOM directly. Instead, it serves as a blueprint that Angular can render conditionally or reuse when needed.

This article dives into what ng-template is, how it works, when to use it, and practical examples that demonstrate its usefulness in building robust Angular applications.

What is ng-template?

The ng-template directive in Angular represents a template fragment—a piece of HTML that Angular can render conditionally or dynamically within the application. Think of ng-template as an invisible wrapper: it provides a way to define HTML markup that Angular will only render if explicitly instructed.

Characteristics of ng-template

  1. Not Rendered by Default: Content inside ng-template isn’t displayed in the DOM unless Angular is instructed to display it.
  2. Structural Directive Support: ng-template works well with structural directives like *ngIf and *ngFor, which conditionally render its content.
  3. Reusability: Templates inside ng-template can be reused in various places throughout your application.
  4. Dynamic Content Rendering: Using Angular’s ViewContainerRef and TemplateRef, ng-template allows dynamic component loading, enhancing modularity and flexibility.

Basic Syntax of ng-template

htmlCopy code<ng-template #templateRef>
  <p>This content is inside an ng-template and will not render by default.</p>
</ng-template>

The #templateRef in the example above is a template reference variable, which allows us to access and render this template programmatically.

Using ng-template with Structural Directives

Angular’s structural directives are great tools for conditionally rendering or looping through content. When combined with ng-template, they offer a powerful way to control what’s displayed in the DOM.

Example 1: Using *ngIf with ng-template

The *ngIf directive allows us to conditionally render content, and ng-template gives us more control over what is displayed if the condition isn’t met.

htmlCopy code<div *ngIf="isLoggedIn; else loginTemplate">
  <p>Welcome back, user!</p>
</div>
<ng-template #loginTemplate>
  <p>Please log in to continue.</p>
</ng-template>

In this example:

  • If isLoggedIn is true, the welcome message is displayed.
  • If isLoggedIn is false, the content inside the loginTemplate ng-template is shown instead.

Example 2: Using *ngFor with ng-template

The *ngFor directive can also be combined with ng-template to display repeated content in a more controlled manner.

htmlCopy code<ng-template ngFor let-item [ngForOf]="items" let-i="index">
  <p>{{ i + 1 }}. {{ item }}</p>
</ng-template>

This renders a list of items where each item has an index, displaying dynamic content in a reusable format.

Advanced Usage of ng-template

Beyond basic conditional rendering, ng-template can handle more advanced scenarios, such as dynamic template rendering, creating reusable templates, and custom structural directives.

Example 3: Dynamic Template Rendering with ngTemplateOutlet

Angular provides the ngTemplateOutlet directive to render ng-template dynamically. This is useful when you want to change templates based on user interactions or application states.

htmlCopy code<ng-container *ngTemplateOutlet="isSpecial ? specialTemplate : regularTemplate"></ng-container>
<ng-template #specialTemplate>
  <p>This is a special template!</p>
</ng-template>
<ng-template #regularTemplate>
  <p>This is a regular template.</p>
</ng-template>

In this example:

  • ngTemplateOutlet dynamically renders the specialTemplate if isSpecial is true, otherwise it renders the regularTemplate.
  • ng-container acts as a placeholder without adding extra HTML to the DOM.

Example 4: Passing Context to ng-template

With ngTemplateOutlet, you can also pass a context object to ng-template, allowing you to send dynamic data to the template at render time.

htmlCopy code<ng-container *ngTemplateOutlet="greetingTemplate; context: { $implicit: userName, age: userAge }"></ng-container>
<ng-template #greetingTemplate let-name let-age="age">
  <p>Hello, {{ name }}! You are {{ age }} years old.</p>
</ng-template>

Here:

  • The context object passes values to greetingTemplate, making it more flexible and reusable.
  • $implicit is a special key in Angular, which allows you to pass a single unnamed variable to the template.

Example 5: Using ng-template with ViewContainerRef and TemplateRef

If you want to control template rendering programmatically in Angular, you can use ViewContainerRef and TemplateRef in a component’s TypeScript file.

typescriptCopy codeimport { Component, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
  selector: 'app-dynamic-template',
  template: `
    <button (click)="toggleTemplate()">Toggle Template</button>
    <ng-template #myTemplate>
      <p>This template is rendered dynamically!</p>
    </ng-template>
  `
})
export class DynamicTemplateComponent {
  @ViewChild('myTemplate') myTemplate!: TemplateRef<any>;
  constructor(private viewContainerRef: ViewContainerRef) {}
  toggleTemplate() {
    if (this.viewContainerRef.length > 0) {
      this.viewContainerRef.clear();
    } else {
      this.viewContainerRef.createEmbeddedView(this.myTemplate);
    }
  }
}

In this example:

  • The ViewChild decorator fetches a reference to the ng-template.
  • ViewContainerRef is injected to control the placement and removal of the template.
  • toggleTemplate() adds or removes the template dynamically based on the button click.

Common Use Cases for ng-template

  1. Reusable UI Patterns: Templates that are used in multiple places can be defined once with ng-template and dynamically rendered as needed.
  2. Conditional UI Blocks: Complex conditionals that would otherwise clutter the DOM can be made cleaner with ng-template.
  3. Dynamic Content Loading: Loading different content or components based on certain conditions, such as user preferences or API responses.
  4. Custom Loading States: Using ng-template to conditionally render loading spinners or fallback content based on data availability.

Best Practices for ng-template

  1. Use ng-template Sparingly: Only use ng-template when necessary to avoid adding complexity. Simple conditional rendering may not always require ng-template.
  2. Define Reusable Templates: For complex, repeated elements, define reusable templates using ng-template and ngTemplateOutlet.
  3. Leverage Context Passing: When using ng-template for dynamic content, consider passing context variables to make templates more adaptable and maintainable.
  4. Avoid Nesting Too Deeply: Overuse of nested ng-template elements can make code hard to read and maintain. Keep the template structure straightforward for clarity.

Conclusion

ng-template is a powerful feature in Angular that enables developers to create reusable, conditional, and dynamic templates efficiently. With the ability to use ng-template alongside structural directives, ngTemplateOutlet, and ViewContainerRef, Angular developers can build complex UI components that remain modular and maintainable.

By understanding and implementing ng-template, you can make your Angular applications more flexible, efficient, and robust. Whether you’re working on dynamic content, conditional rendering, or reusable templates, ng-template is an invaluable tool that every Angular developer should master.

Leave a Reply

Your email address will not be published. Required fields are marked *