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

时间:2017-06-29 09:54:17

标签: angular bootstrapping

愚蠢的提问:

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

@NgModule({
  bootstrap: [AppComponent]
})

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

2 个答案:

答案 0 :(得分:3)

是的,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会创建两个独立的视图树,并将这两个视图附加到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时,将通过以下两个视图:

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

有趣的事情

更令人着迷的是,您可以编程方式将<b-comp>附加到应用程序,而无需在BComponent中指定组件module.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>

答案 1 :(得分:1)

那是因为您可以引导不同的模块同时拥有不同的应用程序。

您可以在此处查看此示例:

  

{{3}}

其中重要的部分是:

  Sub empty_cells()                 
  Dim sht As Worksheet        
  Dim Rrng As Range        
  Dim cell As Range                
  Dim LastRow As Long
  Dim StartCell As Range
  Dim bIsEmpty As Boolean
  Set sht = ThisWorkbook.Worksheets("SS upload")
  Set StartCell = Range("A14")
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  MsgBox (LastRow)
  Set Rrng = Range("A14 : H" & LastRow)
  For Each cell In Rrng
  If IsEmpty(cell) = True Then
  bIsEmpty = True
  Exit For
 End If
 Next cell
If bIsEmpty = True Then
MsgBox "There are empty cells in the file"
Else
MsgBox "All cells have values!"
  End If
 End Sub