user2999287 user2999287 - 7 months ago 157
Javascript Question

Angular 2 understand ViewContainerRef usage with TemplateRef

I am implementing structural directive in Angular 2.
In the docs, I saw that I need to inject the TemplateRef to get the template element and the ViewContainerRef.

class TestDirective {
constructor( private templateRef : TemplateRef<any>,
private viewContainer : ViewContainerRef ) {

// this.viewContainer.createEmbeddedView(this.templateRef);

<template [ngIf]="condition">
Our heroes are true!

In this case what I don't understand which element is the ViewContainerRef?


If you inject ViewContainerRef the element is the host element of TestDirective. If you use @ViewChild(templateVarNameOrType) or @ContentChild(templateVarNameOrType) it's the element where templateVarNameOrType matches.

You should be aware that this.viewContainer.createEmbeddedView() or this.viewContainer.createComponent() creates the element or component as sibling of the element ViewContainerRef points to, not as many expect as child.