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

use*_*127 10 lazy-loading angular angular5

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

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

nir*_*aft 5

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

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

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

      <div>
          <ng-template #viewContainerRef></ng-template>
       </div>
    
    Run Code Online (Sandbox Code Playgroud)

@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;
Run Code Online (Sandbox Code Playgroud)

并动态创建组件:

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;

}
Run Code Online (Sandbox Code Playgroud)

这里有一个适合您的示例:https : //add-or-remove-dynamic-component-parent-child.stackblitz.io