Is it possible to run one Angular 2 app several ti

2019-02-19 00:02发布

I'm making migration from asp.net web forms to Angular 4. I'm making it step by step. Replacing one part and placing it in production. I face a problem with loading same Angular app several times in page. For example with code

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

there is only one loaded app in the page - the first one. How can I make them work both? Any suggestions are welcome

1条回答
放荡不羁爱自由
2楼-- · 2019-02-19 00:30

You can use Applicationref.bootstrap method to do it working:

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

As we can see this method can take rootSelectorOrNode parameter so we can bootstrap the same component twice.

ngDoBootstrap method on your root @NgModule can help us to manually bootstrap our application:

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

See also:

查看更多
登录 后发表回答