ng-content inside ng-template always creates content even if the template is not rendered

2.1k views Asked by At

I am facing a strange bug with a ng-content wrapped in a ng-template.

Let's say I have a component inner-component which I display within a outer-component:

<ng-container *ngIf="condition" [ngTemplateOutlet]="test"></ng-container>
<ng-template #test>
    <inner-component></inner-component>
</ng-template>

If condition=false, then, as expected, my inner-component is never created by Angular (when debugging, ngOnInit() is never called).

Now, if instead I have my outer component as:

<ng-container *ngIf="condition" [ngTemplateOutlet]="test"></ng-container>
<ng-template #test>
    <ng-content></ng-content>
</ng-template>

and, still with condition=false, I write:

<outer-component>
    <inner-component></inner-component>
</outer-component>

Then, to my surprise, the inner-component is created, even if it is never rendered. This is a problem for me because the inner-component (a 3rd party component which I can't modify) really does need to be created when it is rendered in the app.

Can you think of a workaround I could use on the outer component to avoid creating the ng-content, (while still using transclusion obviously - the first solution is not an option).

1

There are 1 answers

4
hyperdrive On

You could move the template to the parent component.

<app-outer>
    <ng-template #test>
        <app-inner></app-inner>
    </ng-template>
</app-outer>

And in your outerComponent get a child reference to the template

@ContentChild('test') testTemplate: TemplateRef<ElementRef>;

Outer html

<ng-container *ngIf="condition" [ngTemplateOutlet]="testTemplate"></ng-container>

Stackblitz