Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to suppress child components initialization on condition in angular?

Tags:

angular

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>
like image 393
Antoniossss Avatar asked Dec 20 '25 23:12

Antoniossss


1 Answers

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>
like image 115
Estus Flask Avatar answered Dec 22 '25 14:12

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!