我有一个动态组件:
动态组件.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{}
我将此模块打包到一个 Angular 包中(使用 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 中的 View 设置为 DynamicComponentModule 中的第一个组件,该组件恰好是 DynamicComponent1。
问题是当我想从 DynamicComponent1 导航到 DynamicComponent2 时。如何做到这一点?
编辑:
这是一个 plnkr,可以向您展示问题: https://embed.plnkr.co/rRCQx1N6nJvr0gBERINs/
最佳答案
您不需要手动加载和编译该模块。您可以使用resetConfig
API与 loadChildren
一起使用。 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>
并从DynamicComponentRoutingModule
中删除dynamicModule
部分:
const routes: Routes = [
{
path: 'dynamicComponent1',
component: DynamicComponent1
},
{
path: 'dynamicComponent2',
component: DynamicComponent2,
}
];
关于angular - 如何使用动态加载模块中的组件动态添加路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47868321/