首页 > 解决方案 > Angular 5:没有路由的组件延迟加载

问题描述

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

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

标签: angularangular5lazy-loading

解决方案


您可以等待用户单击该链接,并在单击事件发生后立即在视图中加载所需的组件。要记住的事情:

  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


推荐阅读