Angular可以有多个引导程序组件吗?

Jul*_*ius 5 bootstrapping angular

愚蠢的问题警报:

在主app.module.ts文件中,我们使用定义了顶层组件的值设置bootstrap参数。因此:

@NgModule({
  bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)

我们告诉我们,当使用我们的模块时,我们的顶级组件是AppComponent。但是为什么要排列成阵列?可以有更多的顶级组件吗?

Max*_*kyi 7

是的,Angular可以具有许多顶级组件。您可以自己轻松检查它:

@Component({selector: 'a-comp', template: `A comp`})
export class AComp {}

@Component({selector: 'b-comp', template: `B comp`})
export class BComp {}


@NgModule({
  imports: [BrowserModule],
  declarations: [AComp, BComp],
  bootstrap: [AComp, BComp]
})
export class AppModule {
}

------------------

<body>
    <a-comp></a-comp>
    <b-comp></b-comp>
</body>
Run Code Online (Sandbox Code Playgroud)

引擎盖下的力学

Angular将创建两个单独的视图树,并将两者都附加到此处的ApplicationRef

PlatformRef_.prototype._moduleDoBootstrap = function (moduleRef) {
        var appRef = (moduleRef.injector.get(ApplicationRef));
        if (moduleRef._bootstrapComponents.length > 0) {
            moduleRef._bootstrapComponents.forEach(function (f) { return appRef.bootstrap(f); });
  --------------------------------

  // will be called two times
  ApplicationRef_.bootstrap = function (componentOrFactory, rootSelectorOrNode) {

  ...
  ApplicationRef.attachView(viewRef: ViewRef): void {
    const view = (viewRef as InternalViewRef);
    this._views.push(view);
    view.attachToAppRef(this);
  }
Run Code Online (Sandbox Code Playgroud)

然后,何时运行更改检测将applicationRef经历以下两个视图:

  ApplicationRef.tick(): void {
    ...
    try {
      this._views.forEach((view) => view.detectChanges());
      ...
Run Code Online (Sandbox Code Playgroud)

令人着迷的东西

什么是更有趣的是,你可以附加<b-comp>到应用程序编程不指定组件BComponentmodule.boostrap: []

export class AComponent {
  constructor(r: ComponentFactoryResolver, app: ApplicationRef) {
    const f = r.resolveComponentFactory(BComponent);
    app.bootstrap(f, 'b-comp');

---------------

@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent],
  entryComponents: [BComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

--------------

<body>
    <a-comp></a-comp>
    <b-comp></b-comp>
</body>
Run Code Online (Sandbox Code Playgroud)