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
