是的,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> 附加到应用程序,而无需在module.boostrap: [] 中指定组件BComponent:
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>