Is it possible to prevent the creation of child components if ng content is missing from the template?

I am trying to create a tab component with a structure like this:

<tabs>
    <tab-item [title]="'Tab 1'">
        **child component that makes database calls in NgOnInit or NgAfterViewInit**
    </tab-item>
    <tab-item [title]="'Tab 2'">
        **child component that makes database calls in NgOnInit or NgAfterViewInit**
    </tab-item>
    <tab-item [title]="'Tab 3'">
        **child component that makes database calls in NgOnInit or NgAfterViewInit**
    </tab-item>
</tabs>

I have conditional logic to ensure that child components are only displayed via ng content if they are on the selected tab with the following snippet:

<ng-content *ngIf="selected"></ng-content>

While this works as expected in terms of the user interface, it seems that the children are still created internally, although they are never displayed. I would like to avoid this, since it causes database calls that will not be needed until the user selects the appropriate tab.

. , ng- ChildComponent, console.log ThirdComponent .

? , , , , Angular, , .

, !

+4
1

, .

, :

<ng-content *ngIf="selected"></ng-content>
<template *ngIf="selected && templateRef" [ngTemplateOutlet]="templateRef"></template>

templateRef :

@Input() templateRef: TemplateRef<any>;

, :

<tabs>
    <tab-item [title]="'Tab 1'">
        **static content**
    </tab-item>
    <tab-item [title]="'Tab 2'" [templateRef]="tab2"></tab-item>
    <tab-item [title]="'Tab 3'" [templateRef]="tab3"></tab-item>
    <template #tab2>
        **child component that makes database calls in NgOnInit or NgAfterViewInit**
    </template>
    <template #tab3>
        **child component that makes database calls in NgOnInit or NgAfterViewInit**
    </template>
</tabs>

, , .

+1

Source: https://habr.com/ru/post/1665665/


All Articles