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).
You could move the template to the parent component.
And in your outerComponent get a child reference to the template
Outer html
Stackblitz