[英]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.