如何使用动态加载的模块中的组件动态添加路由

时间:2017-12-18 12:16:29

标签: angular

我有一个动态组件:

动态component.module.ts

@NgModule({
  imports: [
      DynamicComponentRoutingModule,
      FormsModule,
      CommonModule,
      FormsModule,
  ],
  declarations: [
      DynamicComponent1,
      DynamicComponent2,
  ],
  exports: [DynamicComponent1,DynamicComponent2]
})
export class DynamicComponentModule {
}

及其路由:

动态component.routing.ts

const routes: Routes = [
    {
        path: '',
        children: [
            {   
                path: 'dynamicComponent1',
                component: DynamicComponent1
            },
            {
                path: 'dynamicComponent2',
                component: DynamicComponent2,
            }
        ]
    }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DynamicComponentRoutingModule{}

我将这个模块打包成一个角度包(使用ng-packagr),在我的app.component.ts里面我动态加载它:

@ViewChild('vc', { read: ViewContainerRef }) vc: ViewContainerRef;

constructor(private router: Router, private _compiler: Compiler, private _injector: Injector, private route: ActivatedRoute) {
}

loadModule(path: string) {
    System.import(path).then((module) => {
        console.log(module);
        this._compiler.compileModuleAndAllComponentsAsync(module.DataTypesModule)
            .then((compiled) => {
                const m = compiled.ngModuleFactory.create(this._injector);
                const factory = compiled.componentFactories[0];
                if (factory) {
                    const cmp = factory.create(this._injector, [], null, m);
                    this.cmpRef = this.vc.createComponent(factory);
                }
            })
    });
}

如您所见,我已经加载了DynamicComponentModule并将app.component中的视图设置为DynamicComponentModule中恰好是DynamicComponent1的第一个组件。

问题是当我想从DynamicComponent1导航到DynamicComponent2时。怎么做?

编辑:

这是一个能告诉你问题的plnkr: https://embed.plnkr.co/rRCQx1N6nJvr0gBERINs/

1 个答案:

答案 0 :(得分:1)

您无需手动加载和编译模块。您可以将resetConfig APIloadChildren一起使用。 See the plunker

以下是相关代码:

loadModule() {
    this.router.resetConfig([
        ...this.router.config,
        {
            path: 'dynamicModule',
            loadChildren: './dynamic-component.module.ts#DynamicComponentModule'
        }
    ]);

    this.router.navigateByUrl('dynamicModule/dynamicComponent1');

您还需要将router-outlet添加到my-app模板:

@Component({
    selector: 'my-app',
    template: `
    <div>
      <h2>Hello {{name}}</h2>
      <router-outlet></router-outlet>
    </div>

dynamicModule删除DynamicComponentRoutingModule部分:

const routes: Routes = [
    {
        path: 'dynamicComponent1',
        component: DynamicComponent1
    },
    {
        path: 'dynamicComponent2',
        component: DynamicComponent2,
    }
];