1

I have two completely unrelated components on a page. I do not want to load them as subcomponents under a parent template. How would I load both of them on a single page?

<section>
<h1>Heading</h1>
<the-first-component></the-first-component>
</section>

(lots of html)

<main>
<h1>Another heading</h1>
<the-second-component></the-second-component>
</main>

(lot more html)
ebakunin
  • 3,621
  • 7
  • 30
  • 49

1 Answers1

4

Just call bootstrap for each component

bootstrap(AppComponent1, [ /* providers here */]);
bootstrap(AppComponent2, [ /* providers here */]);

if you want to share data you can use a shared service for example

@Injectable()
class MySharedService {
}

var shared = new MySharedService();

bootstrap(AppComponent1, [provide(MySharedService, {useValue: shared}]);
bootstrap(AppComponent2, [provide(MySharedService, {useValue: shared}]);

This way when a AppComponentx or one of their sub-components or another service has a constructor parameter like

constructor(private myShared: MySharedService) {}

then you have the same global instance available everywhere to be able to easily communicate between the different Angular2 "applications" on your page. See also detect change of nested property for component input

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • See also http://stackoverflow.com/questions/36263181/angular-2-more-than-one-component-on-same-page/36263211#36263211 – Günter Zöchbauer Mar 28 '16 at 18:04
  • If i call bootstrap on all the components and they are not present on the page, i will get an error. Any way to avoid this? My goal is to have multiple reusable components which can be embedded on the page – pfried May 13 '16 at 12:22
  • @pfried I guess wrapping `bootstrap(...)` in a `try`/`catch` or using a custom error handler like explained in http://stackoverflow.com/questions/32488245/custom-exception-handler-in-angular2 should does what you want. – Günter Zöchbauer May 13 '16 at 12:40