user2999287 user2999287 - 1 year ago 327
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download