愚蠢的问题警告:
在我们的主 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>
在不指定组件的情况下以编程方式添加到应用程序 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>
关于angular - Angular 可以有多个 Bootstrap 组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44821879/