[英]Bootstrapping multiple components in Angular2
我的問題與這個問題一致: 引導多個 angular2 模塊時出錯
我的index.html有以下代碼
<app-header>Loading header...</app-header> <app-root>Loading...</app-root> <app-footer>Loading footer...</app-footer>
在我的app.module.ts 中,我提供了這 3 個組件來引導:
bootstrap: [AppComponent,HeaderComponent,FooterComponent]
在我的 main.ts 中,我引導它們
platformBrowserDynamic().bootstrapModule(AppModule);
該應用程序與包含的所有三個模塊一起運行良好。 當它們中的任何一個被刪除時,該應用程序都可以運行,但我在控制台中收到了一些錯誤[img附加]。
我正在嘗試在可以插入和拔出應用程序的同一組件中創建獨立模塊。 例如,頁眉、頁腳和正文模塊。 有些頁面可能不需要標題,所以我可以跳過 app-header 包含。
我的做法對嗎?
我剛找到這個,它工作正常
import { NgModule, Injectable, APP_INITIALIZER, ApplicationRef, Type, ComponentFactoryResolver } from '@angular/core';
import {FooterComponent} from './footercomponent';
import {AppComponent} from './appcomponent';
import {HeaderComponent} from './headercomponent';
const components = [AppComponent, HeaderComponent,FooterComponent];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
entryComponents: components,
providers: []
})
export class AppModule {
constructor(private resolver: ComponentFactoryResolver) { }
ngDoBootstrap(appRef: ApplicationRef) {
components.forEach((componentDef: Type<{}>) => {
const factory = this.resolver.resolveComponentFactory(componentDef);
if (document.querySelector(factory.selector)) {
appRef.bootstrap(factory);
}
});
}
}
模塊方法:
@NgModule({ declarations: [App1], exports: [App1] }) export class App1Module @NgModule({ declarations: [App2], exports: [App2] }) export class App2Module @NgModule({ imports: [App1Module, App2Module], exports: [App1Module, App2Module] }) export class MainModule
如果您需要所有這些主模塊,或者僅包含相關模塊,請包括此主模塊。
盡管您可以為每個組件創建單獨的模塊,並在需要時使用它們或通過導入它們全部使用它們,但您仍然可以繼續引導多個組件,方法是在 bootstrap 的數組索引中一次又一次地提及它們。
例如。)
@NgModule({ imports: [], declarations: [App1, App2, App3], bootstrap: [App1, App2, App3] }) export class BaseModule {}
如果您在開始時就擁有所有引導組件,例如,
<body> <app1>App1</app1> <app2>App1</app2> <app3>App1</app3> </body>
這可能應該有效。
更多信息:
https://plnkr.co/edit/akm7OPahe72Ex9i2ZXej?p=preview
希望能幫助到你。
如果有更多編輯,請告訴我。
馬諾,
我可能會在一塊中引導應用程序:
<app>Loading...</app>
然后為頁眉和頁腳制作組件,並將它們作為子視圖包含在主組件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.