【问题标题】:Angular routes for OTF componentsOTF 组件的角度路由
【发布时间】:2019-02-14 17:24:21
【问题描述】:

我们使用 Angular 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?

我们缺少什么,是否支持这种情况?


非常感谢任何帮助

【问题讨论】:

  • my answer。我很快会写一篇文章,解释为什么我的解决方案有效,以及为什么你的解决方案无效。 Follow me on Twitter 得到通知
  • 谢谢,您的示例适用于我的情况。抱歉回复晚了,会跟进那篇文章:)
  • 酷,祝你好运

标签: angular dynamic routes components


【解决方案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');
    });
  }

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2019-06-23
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多