angular - Angular 可以有多个 Bootstrap 组件吗?

标签 angular bootstrapping

愚蠢的问题警告:

在我们的主 app.module.ts 文件中,我们使用定义顶级组件的值设置引导参数。所以有了这个:

@NgModule({
  bootstrap: [AppComponent]
})

我们告诉当我们的模块被使用时,我们的顶级组件是 AppComponent。但为什么它在数组中?可以有更多的顶级组件......?

最佳答案

是的,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>

引擎盖机制

Angular 将创建两个独立的 View 树并将它们附加到此处的 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);
  }

然后,当更改检测运行时 applicationRef将通过这两个 View :

  ApplicationRef.tick(): void {
    ...
    try {
      this._views.forEach((view) => view.detectChanges());
      ...

迷人的东西

更有趣的是,您可以附加 <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>

关于angular - Angular 可以有多个 Bootstrap 组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44821879/

相关文章:

angular - Angular 6 中的图像轮播

ubuntu - 如何在 Ubuntu 14.04 上安装最新的 Boost 版本?

zend-framework - 如何禁用某些 Zend View Helpers

angularjs - AngularJS 中的 ng-app V/S 数据-ng-app

PHP Composer : what is BootStrap process?

php - Laravel - 将文件上传到数据库

angular - 为 Angular5 添加组件时出错

Angular 2/4 Protractor 调试 e2e 测试

javascript - Nativescript ios - 命令 xcodebuild 失败,退出代码为空

angular - 在 Angular4 库上运行 ngc 时,TsickleCompilerHost 出错