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

时间:2017-08-26 14:18:35

标签: asp.net angular webforms angular-bootstrap

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

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用Applicationref.bootstrap方法来执行此操作:

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

我们可以看到这个方法可以使用rootSelectorOrNode参数,所以我们可以两次引导同一个组件。

ngDoBootstrap上的

@NgModule方法可以帮助我们手动引导我们的应用程序:

@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);
     }
   }
}

另见: