Search code examples
angularangular-directiveangular-template

angular templateRef passed to parent using structural directive not rendering inside parent component


I am trying to render template in a child element of a parent componenet depending on it's type value as explained in this schema

enter image description here

I am passing the ng-template to parent view(my container) using myTemplateDirective

  --myTemplateDirective--
 this.parent.setDirective(this);

 --my-container--
 setDirective(test) {
    this.tmpl = test;
 }

in my container I pass it to my-componenet who has the directive as input and renders it

const element = this.template.renderTemplate(this.data ,this.viewContainerRef);


  renderTemplate(templateData, vcRef) {
this.renderCount++;

const viewData = {
  $implicit: {
    data: templateData,
    renderCount: this.renderCount
  }
};
const childView = vcRef.createEmbeddedView(this.templateRef, viewData);

// =========== WORKAROUND =============
// We have to use private API to force DOM to update
// childView['detectChanges']();
// =========== /WORKAROUND =============


this.cd.detectChanges();

return childView.rootNodes[0];
}

after creating the embeddedView the result I get from return childView.rootNodes[0] is :

<!---->

I have created a plunker containing all the code to better understand the problem plunker sample code


Solution

  • According to your diagram, you seem to have two nested ng-template.

    Angular will transform the following which uses a structural directive:

    <ng-template *myTemplate>
        <div>...</div>
    </ng-template>
    

    to this:

    <ng-template myTemplate>
        <ng-template>
            <div>...</div>
        </ng-template>
    </ng-template>
    

    This might be a problem in your case, if you are trying to render the outer template, as it will only contain a template inside, and thus nothing to render.