October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Create Template Fragments with ng-template in Angular

Create Angular template fragments with ng-template, then render them declaratively with NgTemplateOutlet or programmatically with ViewContainerRef.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Angular’s <ng-template> declares markup that is not rendered until Angular instantiates it. Capture the fragment as a TemplateRef, then render it declaratively with NgTemplateOutlet or imperatively with ViewContainerRef.createEmbeddedView(). Choose the outlet when the fragment and its data fit naturally in template markup; use a view container when TypeScript must control creation.

Declare a fragment with ng-template

An <ng-template> holds prepared template content; placing it in a component template does not display that content by itself. Angular represents the fragment as a TemplateRef. A template reference variable on the element gives you access to it within the template:

As an Amazon Associate I earn from qualifying purchases.

<p>This is rendered normally.</p>

<ng-template #notice>
  <p>This fragment appears only when Angular instantiates it.</p>
</ng-template>

Here, #notice refers to the template fragment, not to a rendered DOM element. You can also obtain a TemplateRef through a query or by injecting it into a directive attached to an <ng-template>. See Angular’s template fragments guide and ng-template API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Render it declaratively with NgTemplateOutlet

Import NgTemplateOutlet from @angular/common in the component’s imports, then use it at the desired insertion point. Angular recommends placing the outlet on an <ng-container>, which groups content without adding a DOM element.

<ng-container *ngTemplateOutlet="notice"></ng-container>

The outlet instantiates the fragment at its location. This is usually the clearest choice when the template can specify which fragment to render and what context to pass. See Angular’s ng-container guide.

Pass data through the fragment context

A fragment can declare local variables with let- syntax. The variable name after let- is local to the fragment; the value after = identifies the matching property in the context object.

<ng-template #greeting let-name="person">
  <p>Hello, {{ name }}.</p>
</ng-template>

<ng-container
  *ngTemplateOutlet="greeting; context: { person: 'Rae' }">
</ng-container>

In this example, let-name="person" reads the person property, so the fragment displays “Hello, Rae.” If you write let-item without naming a property, Angular reads the $implicit property from the context object. The same context mapping applies when creating an embedded view in TypeScript.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose between the outlet and ViewContainerRef

Approach Use it when How rendering is controlled
NgTemplateOutlet The fragment and its context can be selected in template markup. Declaratively, at the outlet location, commonly an <ng-container>.
ViewContainerRef.createEmbeddedView() Component or directive code needs to decide when to instantiate the fragment. Imperatively, at the injected view container. Angular documents the created view as the next sibling of the component or directive that injected that container.

This is a choice about where to express rendering logic, not a performance comparison. Angular documents both approaches in its template fragments guide.

Create the view in TypeScript

Inject a ViewContainerRef and call createEmbeddedView(templateRef, context) when your component or directive decides to render the fragment. For example, a directive can receive an optional template and create a view once it has one:

import { Directive, TemplateRef, ViewContainerRef, inject } from '@angular/core';

@Directive({ selector: '[appRenderFragment]' })
export class RenderFragmentDirective {
  private readonly viewContainer = inject(ViewContainerRef);

  render(template: TemplateRef<unknown> | null | undefined): void {
    if (!template) return;

    this.viewContainer.createEmbeddedView(template);
  }
}

The null check matters when the template is optional: do not attempt to create an embedded view until you have a TemplateRef. To provide local variables, pass a context object as the second argument:

this.viewContainer.createEmbeddedView(template, {
  $implicit: 'Rae',
  role: 'editor',
});

A fragment could read those values as let-name and let-role="role", respectively.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understand declaration scope and injector behavior

Rendering a fragment somewhere else does not change which component its expressions belong to: they continue to be evaluated against the component where the fragment was declared. Angular states: “Expressions or statements in a template fragment are evaluated against the component in which the fragment is declared, regardless of where the fragment is rendered.” See the Angular guide.

Injector context is a separate concern. By default, a fragment uses the injector from its declaration location. The NgTemplateOutlet API accepts a custom injector; its 'outlet' option makes the embedded view inherit from the outlet location instead. Angular notes this can help with recursive structures and providers scoped at each outlet level. Changing injector context does not change the component scope used to evaluate the fragment’s expressions. See the NgTemplateOutlet API.

How structural directive shorthand relates

An asterisk-prefixed structural directive is shorthand for an <ng-template> wrapper around the host element and its contents. For example, applying *myDirective to a <section> is shorthand for an <ng-template myDirective> containing that section. Structural directives use this mechanism to create content conditionally or multiple times; the shorthand is not a sign that an ordinary template reference variable is a DOM reference. Angular explains the relationship in its template fragments guide.

Check version-sensitive query syntax

If you obtain a fragment through a component query rather than a template reference variable, use the query API supported by your Angular version. The current guide uses signal-style query APIs, while Angular’s v18 guide demonstrates decorator-based @ViewChild. The declaration and rendering concepts are the same, but query syntax is version-sensitive.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.