4

I am implementing the structural directive in Angular2. 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?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

2

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    You can expand your answer to be with examples please, I see many people struggling with this question. thanks. –  Oct 25 '16 at 06:44
  • The @ViewChild(templateVarNameOrType) or @ContentChild(templateVarNameOrType), and you have duplicate this.viewContainer.createEmbeddedView() code –  Oct 25 '16 at 06:47
  • Thanks for the hint. Was a copy-paste error. Perhaps http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 fills the missing gaps. – Günter Zöchbauer Oct 25 '16 at 06:48
  • 1
    And what if I need to create the element as a child? –  Oct 25 '16 at 06:49
  • You need a `ViewContainerRef` of an element inside the child but I don't know a way to get that, except when the child provides one that it gets itself by `@ViewChild()`. – Günter Zöchbauer Oct 25 '16 at 06:54