So what I wanted to do is to have simple conditional wrapper component with template like this:
<ng-container *ngIf="condition; else falseCondition">
<ng-content *ngIf="condition"></ng-content>
</ng-container>
<ng-template #falseCondition>
<div class="div">
<div class="col-xs-12">
<p translate="translate" class="text-center">{{message}}</p>
</div>
</div>
</ng-template>
and I wanted to use it like this:
<myComponent [condtion]="someCondition" [message]="some message">
<someOtherComponent [bindings]....></someOtherComponent>
</myComponent>
However even if someCondition is false and some message gets displayed like expected, someOtherComponent gets initialized. Is there a way to supress that initialization? I was hoping it will not get created at all if condition is false.
It works as expected if I dont use my wrapper component (like below), but plain *ngIf with else template - other component is not initialized at all then.
<ng-container *ngIf="someCondition">
<!-- this works just fine -->
<someOtherComponent [bindings]....></someOtherComponent>
</ng-container>
Considering that myComponent is not a directive but a component that should have its own template, it cannot prevent its contents from being compiled the same way as ngIf directive does.
This can be solved by supplying <ng-template> as component contents:
@Component({
selector: 'myComponent',
template: `
<ng-container [ngTemplateOutlet]="template" *ngIf="condition; else falseCondition">
<ng-content *ngIf="condition"></ng-content>
</ng-container>
...
`,
})
class MyComponent {
@ContentChild(TemplateRef) template;
...
}
And using it like:
<myComponent [condtion]="someCondition" [message]="some message">
<ng-template>
<someOtherComponent [bindings]....></someOtherComponent>
</ng-template>
</myComponent>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With