OTF组件的角形路线

时间:2018-09-10 09:43:47

标签: angular dynamic routes components

我们使用的是角度6,使用以下代码动态创建组件并为其定义路线:

const template = '<span>generated on the fly: {{name}}</span>';
const tmpCmp = Component({ template: template })(class {
  });
const tmpModule = NgModule({ declarations: [tmpCmp] })(class {
  });

await this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
  .then((factories) => {
    const f = factories.componentFactories[0];
    const cmpRef = this.vc.createComponent(tmpCmp);
    cmpRef.instance.name = 'dynamic';

    appRoutes.push({ path: 'dynamic', component: tmpCmp});

  })

this.router.resetConfig(appRoutes);

导航到动态创建的组件的url时,会出现错误:

  

没有为ConfirmComponent找到组件工厂。您是否将其添加到   @ NgModule.entryComponents?

我们缺少什么,是否支持此方案?


任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这是您的操作方式:

  ngOnInit() {
    const template = '<span>generated on the fly: {{name}}</span>';
    const tmpCmp = Component({template: template})(class {
    });

    const routes = [{path: '', component: tmpCmp}];
    const tmpModule = NgModule({imports: [RouterModule.forChild(routes)], declarations: [tmpCmp]})(class {
    });

    this.compiler.compileModuleAsync(tmpModule).then((ngModuleFactory) => {

      const appRoutes = [...this.router.config];

      const route = {
        path: 'dynamic',
        loadChildren() {
          return ngModuleFactory;
        }
      };

      appRoutes.push(route);

      this.router.resetConfig(appRoutes);

      // test navigation
      this.router.navigateByUrl('/dynamic');
    });
  }