如果模板中不存在 ng-content ,是否可以阻止创建子组件?

JKa*_*r11 5 angular

我正在尝试创建一个结构类似于以下的选项卡组件:

<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>
Run Code Online (Sandbox Code Playgroud)

我有条件逻辑来确保子组件仅通过 ng-content 呈现(如果它们位于具有以下代码片段的选定选项卡上):

<ng-content *ngIf="selected"></ng-content>
Run Code Online (Sandbox Code Playgroud)

虽然从 UI 角度来看这按预期工作,但子元素似乎仍在内部创建,即使它们从未呈现。这是我想避免的事情,因为它会导致在用户选择适当的选项卡之前不需要数据库调用。

我创建了一个大大简化的示例来说明这一点。正如您所看到的,我已经注释掉了 ChildComponent 模板中的 ng-content,但从 ThirdComponent 对 console.log 的调用仍在触发。

有什么办法可以防止这种情况发生吗?我可能可以在选项卡中显示的组件上创建一个界面,然后调用自定义方法来触发数据库调用,而不是使用内置的 Angular 生命周期方法,但如果可能的话,我想避免这种情况。

感谢您的任何帮助,您可以提供!

JKa*_*r11 5

我发现这篇文章对解决我的问题非常有帮助。

我将选项卡项组件的模板更改为如下所示:

<ng-content *ngIf="selected"></ng-content>
<template *ngIf="selected && templateRef" [ngTemplateOutlet]="templateRef"></template>
Run Code Online (Sandbox Code Playgroud)

将 templateRef 作为输入属性:

@Input() templateRef: TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)

要使用此组件,我现在可以执行以下操作:

<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>
Run Code Online (Sandbox Code Playgroud)

仅当选择选项卡时才会加载模板内的任何内容,从而防止初始页面加载过重。