Angular 2: How to conditionally load a Component in a Route asynchronously?

前端 未结 6 651
花落未央
花落未央 2021-01-31 10:39

I\'d like to attach a component to a route asynchronously, given a condition.

The following example, which works (but is asynchronous), loads one compon

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 10:55

    You could create a generic.module.ts which will have both components in declarations array:

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { UserDashboardComponent }  from './user-dashboard.component'
    import { AdminDashboardComponent } from './admin-dashboard.component    
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ UserDashboardComponent,AdminDashboardComponent ]
    })
    export class GenericModule { }
    

    this way you will have a module that contains the modules which you want to load.

    Now next step will be to load them asynchronously using compiler: inside your component do following:

    import {GenericModule} from './generic.module';
    import { Component, Input,ViewContainerRef, Compiler, NgModule,ModuleWithComponentFactories,OnInit,ViewChild} from '@angular/core';
    @Component({
      selector: 'generic',
      template: '
    ' }) export class App implements AfterViewInit { @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef; constructor(private compiler: Compiler) {} ngAfterViewInit() { this.createComponent('Example template...'); } private createComponent(template: string,role:string) { @Component({template: template}); const mod = this.compiler.compileModuleAndAllComponentsSync(GenericModule); const factory = mod.componentFactories.find((comp) => //you can add your comparison condition here to load the component //for eg. comp.selector===role where role='admin' ); const component = this.target.createComponent(factory); } }

    Hope this helps.

提交回复
热议问题