Angular 5:没有路由的组件的延迟加载

时间:2018-06-01 17:07:14

标签: angular angular5 lazy-loading

在我的网络应用程序中,我有一个"条款和条件"通过链接打开的弹出窗口单击页脚(因此它是核心组件)。 弹出窗口包含多个选项卡,每个选项卡都是一个非常大的模板文件。

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

1 个答案:

答案 0 :(得分:4)

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

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

     entryComponents: [
        ChildComponent
      ],
    
  3. 确保在组件中引用占位符,并动态附加条款和条件组件。

      <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-or-remove-dynamic-component-parent-child.stackblitz.io