How to bootstrap two Modules using bootstrapModule() in Angular2?

2k Views Asked by At

Normally this is how a Module is integrated or bootstrapped with the main.ts.

import {platformBrowserDynamic} from'@angular/platform-browser-dynamic'

import {AppModule} from './app.module'

platformBrowserDynamic().bootstrapModule(AppModule)

But in case we have tow modules say :

  1. AppModule- which works with the UI related changes/ modificaitons
  2. DataModule- which works to communicate/modify/display data related interfaces

Both AppModule and DataModule handle the UI modificaitons but being concerned with respective UI modification objectives, I want to work with two modules but at the same time. How shall I begin with?

Will this approach be able to render both modules and perform independent operations?

at index.html

 ...
 ...
 <body class="container">
  <!--Listing Selectors for loading App-Module -->
  <events-app></events-app>
  <events-list></events-list>
  <!-- listing Selectors for loading Data-Module -->
  <events-data></events-data>
  <filter-data></filter-data>
 </body>
 ...
 ...

at main.ts

import {platformBrowserDynamic} from'@angular/platform-browser-dynamic'
import {AppModule} from './app.module'
import {DataModule} from './data.module'

platformBrowserDynamic().bootstrapModule(AppModule, DataModule)
1

There are 1 best solutions below

2
On

Well I've did something like in my Angular 4 app by just doing some configuration in main.ts and tsconfig.json and its working perfectly fine. You can follow the below steps and can try.

Step 1: Create your module and declare root components which you want to load when you bootstrap that module.

Ex. Here I've created user.module.ts

import { NgModule }      from '@angular/core';

// root component of usermodule
import { UserAppComponent }   from './userapp.component';

@NgModule({
  imports:[FormsModule,HttpModule],
  declarations:[UserAppComponent],
  providers:[],
  bootstrap:[UserAppComponent]
})
export class UserModule { }

Step 2: Go to main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import { UserModule } from './user.module';

window.platform = platformBrowserDynamic();
window.AppModule = AppModule;
window.UserModule = UserModule;

Step 3: Go to tsconfig.json and insert your newly created module and component in "files" array

"files":[
    //....your other components ...//
    "myapp/user.module.ts",  
    "myapp/userapp.component.ts",           
  ]

Step 4: Now you are ready to bootstrap angular module wherever you want from your .js file. Like I've bootstrap like this from my .js file. Bootstrapping may differ based on your requirement but step 1 to 3 should be same.

window.platform.bootstrapModule(window.UserModule);