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

问题描述 投票:2回答:1

我有一个动态组件:

动态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的第一个组件。

问题是当我想从动态组件1导航到动态组件2.如何做到这一点?

编辑:

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

angular
1个回答
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,
    }
];
© www.soinside.com 2019 - 2024. All rights reserved.