是否可以在一个页面中多次运行一个Angular2个应用程序?

Is it possible to run one Angular 2 app several times in one page?

我正在从 asp.net 网络表单迁移到 Angular 4。我正在逐步完成。更换一个零件并将其投入生产。我在页面中多次加载相同的 Angular 应用程序时遇到问题。例如代码

<root tag="table-ep-component" data="5800"></root>
<root tag="table-ep-component" data="3333"></root>

页面中只有一个加载的应用程序 - 第一个。我怎样才能让它们同时工作?欢迎任何建议

您可以使用 Applicationref.bootstrap 方法使其工作:

abstract bootstrap<C>(
  componentFactory: ComponentFactory<C>|Type<C>,
  rootSelectorOrNode?: string|any): ComponentRef<C>;

正如我们所见,此方法可以采用 rootSelectorOrNode 参数,因此我们可以 bootstrap 相同的组件两次。

ngDoBootstrap root 上的方法 @NgModule 可以帮助我们手动 bootstrap 我们的应用程序:

@NgModule({
   declarations: [AppComponent],
   imports: [BrowserModule], 
   entryComponents: [AppComponent]
})
export class MenuModule {
   ngDoBootstrap(appRef: ApplicationRef) {
     const rootElements = document.queryselectorAll('root');
     // cast due to https://github.com/Microsoft/TypeScript/issues/4947
     for (const element of rootElements as any as HTMLElement[]){
       appRef.bootstrap(AppComponent, element);
     }
   }
}

另请参阅:

  • Angular 2 stand alone components
  • Changing shared data between root modules