Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrapping multiple components in Angular2

My question is inline with this question: Error when bootstrapping multiple angular2 modules

My index.html has the following code

  <app-header>Loading header...</app-header>
  <app-root>Loading...</app-root>
  <app-footer>Loading footer...</app-footer>

In my app.module.ts, I supply those 3 components to bootstrap:

bootstrap: [AppComponent,HeaderComponent,FooterComponent]

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]. enter image description here

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.

Is my approach right?

like image 651
Manoj Amalraj Avatar asked Jan 16 '17 16:01

Manoj Amalraj


1 Answers

I just found this and it works fine

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);
            }
        });
    }
}
like image 60
N1gthm4r3 Avatar answered Sep 30 '22 00:09

N1gthm4r3