代码之家  ›  专栏  ›  技术社区  ›  Vikas Bansal

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

  •  8
  • Vikas Bansal  · 技术社区  · 9 年前

    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,这个问题听起来可能很傻:)

    2 回复  |  直到 9 年前
        1
  •  11
  •   Max Koretskyi    9 年前

    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
    

    @NgModule({
        providers: [ServiceSharedBetweenRootComponents]
    }
    export class AppModule {}
    

    然后您可以将其注入每个根组件:

    export class AComponent {
        constructor(service: ServiceSharedBetweenRootComponents)
    
        2
  •  3
  •   yurzui    9 年前

    不可以。您可以在应用程序中实例化多个组件作为入口点。

    例子: https://stackoverflow.com/a/36566919/5706293

    下面是一个如何在根组件之间通信的示例

    推荐文章