加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:08:54 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个具有类似于此结构的制表符组件: 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
我正在尝试创建一个具有类似于此结构的制表符组件:

<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的角度来看这是预期的,但是看起来子元素仍在内部创建,即使它们从未被渲染过.这是我想要避免的,因为它导致在用户选择适当的选项卡之前不需要的数据库调用.

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

有没有办法防止这种情况发生?我可以在组件上创建一个接口,它将显示在选项卡中,然后调用自定义方法来触发数据库调用,而不是使用内置的Angular生命周期方法,但我想尽可能避免这种情况.

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

解决方法

我发现 this article对解决我的问题非常有帮助.

我将tab-item组件的模板更改为如下所示:

<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>

只有在选中选项卡时才会加载模板内部的任何内容,从而防止极大的初始页面加载.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读