user2999287 user2999287 - 1 month ago 37
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">
<p>
Our heroes are true!
</p>
</template>


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

Answer

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.