问题描述
我的问题与以下问题一致:引导多个angular2模块时出错
My question is inline with this question:Error when bootstrapping multiple angular2 modules
我的 index.html 具有以下代码
<app-header>Loading header...</app-header>
<app-root>Loading...</app-root>
<app-footer>Loading footer...</app-footer>
在我的 app.module.ts 中,我提供了这三个组件进行引导:
In my app.module.ts, I supply those 3 components to bootstrap:
bootstrap: [AppComponent,HeaderComponent,FooterComponent]
在我的main.ts中,我引导了它们
and in my main.ts, I bootstrap them
platformBrowserDynamic().bootstrapModule(AppModule);
该应用程序在包括的所有三个模块中都可以正常工作.将其中任何一个删除后,该应用程序都可以运行,但在控制台中收到的错误很少.
The application works fine with all the three modules included. When either of them is removed, the app works but I receive few errors in the console[img attached].
我正在尝试在同一组件中创建独立的模块,这些模块可以插入应用程序或从应用程序中插入.例如,一个页眉,页脚和主体模块.某些页面可能不需要标题,因此我可以跳过app-header包含.
I am trying to create independent modules within the same component that can be plugged in and out of the application. Like for example, a header, footer and body module. Some pages may not need the header, so I can skip the app-header include.
我的方法正确吗?
推荐答案
我刚刚发现此,效果很好
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);
}
});
}
}
这篇关于在Angular2中引导多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!