据我所知,应用程序只能有一个入口点.如下面给出的代码片段所示,我们在bootstrap键中传递一个数组,该数组决定了应用程序的入口点.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent,MyComboboxComponent,CollapsibleDirective,CustomCurrencyPipe],imports: [BrowserModule],providers: [UserService,LessonsService],bootstrap: [AppComponent] }) export class AppModule { }
P.S:我正在学习Angular 2,这个问题可能听起来很傻:)
解决方法
您可以根据需要传递任意数量的引导程序组件.您将最终得到几个独立的组件树:
bootstrap: [AComponent,BComponent] RootModuleInjector | | ApplicationRef.views / \ / \ AComponent BComponent
另见What are the implications of bootstrapping multiple components
运行更改检测时,Angular将分别对每个树运行更改检测:
class ApplicationRef { tick(): void { ... try { this._runningTick = true; // here this._views.length equals to 2 this._views.forEach((view) => view.detectChanges());
如果要执行以下操作,甚至可以手动将新的根组件添加到ApplicationRef:
const componentRef = componentFactoryResolver.resolveComponentFactory(SomeComponent) applicationRef.attachView(componentRef.hostView); RootModuleInjector | | ApplicationRef.views / | \ / | \ AComponent SomeComponent BComponent
如果需要在根组件之间共享一些数据,可以在根模块上定义一个提供程序,用于创建RootModuleInjector:
@NgModule({ providers: [ServiceSharedBetweenRootComponents] } export class AppModule {}
然后你就可以将它注入每个根组件:
export class AComponent { constructor(service: ServiceSharedBetweenRootComponents)