角度5:无需路由即可延迟加载组件 [英] Angular 5: Lazy-loading of component without routing

查看:79
本文介绍了角度5:无需路由即可延迟加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web应用程序中,我有一个条款和条件"弹出窗口,通过单击页脚中的链接打开(因此这是一个核心组件). 弹出窗口由几个选项卡组成,每个选项卡都是一个很大的模板文件.

In my web application I have a "Terms and Conditions" popup that opens by link click in the footer (so it's a core component). Popup comprises of several tabs, each of them is a pretty big template file.

我想知道是否可以将选项卡模板移动到单独的块中并组织它们的延迟加载?我不确定默认的Angular延迟加载是否可以接受,因为我不想为弹出窗口设置单独的路径.

I wonder if it's possible to move tab templates to separate chunk and organize their lazy-loading? I'm not sure if default Angular lazy-loading is acceptable for me because I don't want to have separate route for the popup.

推荐答案

您可以等待用户单击链接,并在发生Click事件后立即将所需的组件加载到视图中. 注意事项:

You can wait for the user to click on the link and as soon as Click Event occurs, load the required component in the view. Things to keep in mind:

  1. 您需要为视图中的组件定义一个占位符.
  2. 条款和条件组件需要定义为其模块或使用模块的入门级组件.

 entryComponents: [
    ChildComponent
  ],

  • 确保在组件中引用占位符,并动态附加条款和条件组件.

  • Make sure to refer to the placeholder in your component and attach the terms and condition component dynamically.

      <div>
          <ng-template #viewContainerRef></ng-template>
       </div>
    

  • @ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;
    

    并动态创建组件:

    createComponent() {
    
        let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
        let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
        let currentComponent = componentRef.instance;
    
        currentComponent.selfRef = currentComponent;
      // to track the added component, you can reuse this index to remove it later
        currentComponent.index = ++this.index; 
    
        // providing parent Component reference to get access to parent class methods
        currentComponent.compInteraction = this;
    
    }
    

    这里有一个示例: https://add或删除动态组件父项child.stackblitz.io

    这篇关于角度5:无需路由即可延迟加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆