我正在尝试创建一个结构类似于此的选项卡组件:
<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>
我有条件逻辑来确保子组件仅通过 ng-content 呈现,前提是它们位于带有以下代码段的选定选项卡上:
<ng-content *ngIf="selected"></ng-content>
虽然从 UI 的 Angular 来看这符合预期,但看起来子元素仍在内部创建,即使它们从未被渲染过。这是我想避免的事情,因为它会导致在用户选择适当的选项卡之前不需要的数据库调用。
我创造了一个伟大的simplified example来说明这一点。如您所见,我已经从 ChildComponent 的模板中注释掉了 ng-content,但是从 ThirdComponent 对 console.log 的调用仍在触发。
有什么办法可以防止这种情况发生吗?我可能会在将显示在选项卡中的组件上创建一个界面,然后调用自定义方法来触发数据库调用,而不是使用内置的 Angular 生命周期方法,但我想尽可能避免这种情况。
感谢您提供的任何帮助!
最佳答案
我找到了 this article对解决我的问题非常有帮助。
我将选项卡项组件的模板更改为如下所示:
<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>
只有在选择选项卡时才会加载模板内的任何内容,从而防止初始页面加载非常繁重。
关于angular - 如果模板中不存在 ng-content,是否可以阻止创建子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41453727/