为什么@NgModule中的"bootstrap"键是一个数组?

Vik*_*sal 7 angular

据我所知,应用程序只能有一个入口点.如下面给出的代码片段所示,我们在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 {

}
Run Code Online (Sandbox Code Playgroud)

PS:我正在学习Angular 2,这个问题可能听起来很傻:)

Max*_*kyi 8

您可以根据需要传递任意数量的引导程序组件.您将最终得到几个独立的组件树:

bootstrap: [AComponent, BComponent]

        RootModuleInjector
                |
                |
       ApplicationRef.views
       /                   \
      /                     \
   AComponent              BComponent
Run Code Online (Sandbox Code Playgroud)

另请参阅引导多个组件的含义

运行更改检测时,Angular将分别对每个树运行更改检测:

class ApplicationRef {
   tick(): void {
    ...
    try {
      this._runningTick = true;
      // here this._views.length equals to 2
      this._views.forEach((view) => view.detectChanges());
Run Code Online (Sandbox Code Playgroud)

ApplicationRef如果您想要,您甚至可以手动添加新的根组件:

const componentRef = componentFactoryResolver.resolveComponentFactory(SomeComponent)
applicationRef.attachView(componentRef.hostView);

        RootModuleInjector
                |
                |
       ApplicationRef.views
       /        |           \
      /         |            \
AComponent  SomeComponent   BComponent
Run Code Online (Sandbox Code Playgroud)

如果需要在根组件之间共享一些数据,可以在根模块上定义一个提供程序,用于创建RootModuleInjector:

@NgModule({
    providers: [ServiceSharedBetweenRootComponents]
}
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

然后你就可以将它注入每个根组件:

export class AComponent {
    constructor(service: ServiceSharedBetweenRootComponents)
Run Code Online (Sandbox Code Playgroud)