Bootstrap two apps in same page using angular 2

2020-04-10 14:46发布

问题:

I am trying to bootstrap two angular2 apps in the same page. I have tried doing that using platformBrowserDynamic.bootstrapModule(). But it's throwing me error as "Tried to find the bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options."

//Main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';

import { AppModule1 } from './app1/app.module1';
import { AppModule2 } from './app2/app.module2';

import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule1 );
platformBrowserDynamic().bootstrapModule(AppModule2 );

So I tried bootstrapping AppModule2 through AppModule1 as given below which worked.

//app1.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppService } from './app.service';

import { App1RoutingModule }  from '../app1/app1-routing.module';
import { App1Component } from '../app1/app1.component';

import { App2Module }  from '../app2/app2.module';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    App1RoutingModule,
App2Module
  ],
  declarations: [App1Component],
  providers: [AppService],
  bootstrap: [App1Component ]
})
export class App1Module { }

platformBrowserDynamic().bootstrapModule(AppModule2);

Though above solution worked and I could create build, but when deployed on Tomcat it did not work.

How to bootstrap 2 apps in the same screen?

回答1:

You can bootstrap two different modules on the same page. Your first attempt should work. Here is the plnkr with two modules bootstrapped on the same page.

app.ts:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

@Component({
  selector: 'my-app2',
  template: `
    <div>
      <h2>Hello2 {{name}}</h2>
    </div>
  `,
})
export class App2 {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App2 ],
  bootstrap: [ App2 ]
})
export class AppModule2 {}

main.ts:

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule, AppModule2 } from './app';

platformBrowserDynamic().bootstrapModule(AppModule)
platformBrowserDynamic().bootstrapModule(AppModule2)


标签: angular