createEmbeddedView adds an embedded view to a ViewContainerRef using a TemplateRef. The view contains the template’s elements, directives, bindings, and expressions, and the method returns a ViewRef for later management. section 15.2.1
Use the method when a directive needs to create or repeat template content:
- Pass the TemplateRef representing an ng-template element. section 15.2.1
- Optionally pass a context object, including $implicit data for a template variable, and an index for insertion. section 15.3
- Call clear when previously created views should be removed from the container. section 15.2.1
- Reuse one template to create multiple views, such as one table row for each data item. section 15.3
Creating views for an iterator
A structural directive injects ViewContainerRef and TemplateRef, clears the container, then creates one view per data item. The context object's $implicit property supplies the value for let-item. ngOnInit() { this.container.clear(); for (let i = 0; i < this.dataSource.length; i++) { this.container.createEmbeddedView( this.template, new PaIteratorContext(this.dataSource[i]) ); } } class PaIteratorContext { constructor(public $implicit: any) { } } 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, including the TemplateRef and ViewContainerRef constructor parameters, conditional creation, and clearing. section 15.2.1
