How to lazy load Angular 2 components in a TabView (PrimeNG)?

前端 未结 5 853
野的像风
野的像风 2020-12-30 16:37

It is my app.component.ts:

import { Component } from \'@angular/core\';

@Component({
    templateUrl: \'app/app.component.html\',
    selector: \'my-app\'
}         


        
5条回答
  •  独厮守ぢ
    2020-12-30 16:49

    You can use SystemJsNgModuleLoader which is used in angular2 routing

    Live Plunker

    First you can write component which will load module:

    @Component({
      selector: 'dynamic-container',
      template: `
        
        
    `, styles: [` .loader { position: relative; min-height: 100px; } .loader:after { content: 'Loading module. Please waiting...'; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } `] }) export class DynamicContainerComponent implements OnDestroy { @ViewChild('container', { read: ViewContainerRef }) vcRef: ViewContainerRef; loaded: boolean; constructor(private moduleLoader: SystemJsNgModuleLoader) { } compRef: ComponentRef; @Input() modulePath: string; @Input() moduleName: string; _inited: boolean set inited(val: boolean) { if(val) { this.loadComponent(); } this._inited = val; }; get inited() { return this._inited; } loadComponent() { this.moduleLoader.load(`${this.modulePath}#${this.moduleName}`) .then((moduleFactory: NgModuleFactory) => { const vcRef = this.vcRef; const ngModuleRef = moduleFactory.create(vcRef.parentInjector); const comp = ngModuleRef.injector.get(LazyLoadConfig).component; const compFactory = ngModuleRef.componentFactoryResolver.resolveComponentFactory(comp); this.compRef = vcRef.createComponent(compFactory, 0, ngModuleRef.injector); this.loaded = true; }); } ngOnDestroy() { this.compRef.destroy(); } }

    And then use it in your component:

    @Component({
      selector: 'my-app',
      template: `
        

    How to lazy load Angular 2 components in a TabView (PrimeNG)?

    ` }) export class AppComponent { @ViewChildren(DynamicContainerComponent) dynamicContainers: QueryList; handleChange(e) { let dynamicContainer = this.dynamicContainers.toArray()[e.index - 1]; if (!dynamicContainer || dynamicContainer.inited) return; // prevent fast clicking and double loading dynamicContainer.inited = true; } }

    See also

    • How to manually lazy load a module?

提交回复
热议问题