liveBook · Manning

TemplateRef

As explained in Pro Angular 16

TemplateRef is an Angular object representing a template that can be instantiated as one or more embedded views.

TemplateRef represents the contents of an <ng-template> element. Structural directives receive it through their constructor and pass it to ViewContainerRef when they need to create embedded views. section 15.2.1

Use TemplateRef with a view container to control how template content becomes part of the rendered document:

  • Call createEmbeddedView(template) to instantiate the template and insert its content. section 15.2.1
  • Call clear() to remove the views created from the template. section 15.2.1
  • Reuse one TemplateRef to create multiple views, supplying a context object for each view. section 15.3

Conditional and repeated templates

A conditional directive injects ViewContainerRef and TemplateRef, then calls this.container.createEmbeddedView(this.template) when its expression is true and this.container.clear() otherwise. An iterating directive calls createEmbeddedView with the same template and a context containing $implicit, producing one tailored view for each data item. section 15.2.1 section 15.3

Listing 15.5. The contents of the structure.directive.ts file in the src/app folder
import {
    Directive, SimpleChanges, ViewContainerRef, TemplateRef, Input
} from "@angular/core";
 
@Directive({
    selector: "[paIf]"
})
export class PaStructureDirective {
 
    constructor(private container: ViewContainerRef,
        private template: TemplateRef<Object>) { }
 
    @Input("paIf")
    expressionResult: boolean | undefined;
 
    ngOnChanges(changes:  SimpleChanges) {
        let change = changes["expressionResult"];
        if (!change.isFirstChange() && !change.currentValue) {
            this.container.clear();
        } else if (change.currentValue) {
            this.container.createEmbeddedView(this.template);
        }
    }
}

Inspect the complete structural-directive implementation showing TemplateRef injection, conditional view creation, and removal. section 15.2.1

How Pro Angular 16 covers it

How deep it goes
Explains constructor injection, embedded-view creation, clearing, reuse, and context data, but defers broader ViewContainerRef management details.
Examples
Uses custom conditional and iterating directives to render table content from a boolean expression or product data source.
What it assumes
Assumes Angular directive and binding basics while demonstrating template creation, view containers, and implicit context data.
What you can do after
Build it from scratch by injecting TemplateRef and ViewContainerRef into custom structural directives.
How it connects
Connects TemplateRef to ng-template, embedded views, ViewContainerRef, structural directives, and template context.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.