【发布时间】:2017-12-21 15:13:11
【问题描述】:
我有一个动态组件:
动态组件.module.ts
@NgModule({
imports: [
DynamicComponentRoutingModule,
FormsModule,
CommonModule,
FormsModule,
],
declarations: [
DynamicComponent1,
DynamicComponent2,
],
exports: [DynamicComponent1,DynamicComponent2]
})
export class DynamicComponentModule {
}
及其路由:
动态组件.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/
【问题讨论】:
-
嘿,为什么要手动加载模块而不是使用
loadChildren作为路由器配置的一部分? -
嗨@AngularInDepth.com,我想在运行时动态加载模块,因为它在设计时是未知的。
-
那么你想在动态加载模块附带的路由树中注册额外的路由吗?
-
@AngularInDepth.com 我添加了一个显示问题的 plnkr:embed.plnkr.co/rRCQx1N6nJvr0gBERINs,是的,因为我已经动态加载了模块,我希望它的路由被注册路线树。
标签: angular