-1

I have 2 components A and B. When I start the application, a div slides on the page and component A is loaded via a partial view on the div. When i click on the button in template of component A, another div slides out. I want to display the component B on this div. How do i achieve this? I cannot use routing as routing would mean I have to place both of these components under a parent component. I want these both components to be independent of each other but still exist on the same page in different divs.

Basically I have an MVC Structure starting at the Index page. Index page has a div which contains partial view Home.cshtml Home.cshtml->

<app1>
  Loading
  </app1>

Also Index page has another div which contains partial view Contacts.cshtml. Contacts.cshtml->

<app2>
    Loading..
</app2>

Both the divs are next to each other. How can I load both the components at the same time on different divs in the same page. Both templates just displays some text.

1 Answers1

1

You can use one of these approaches

https://stackoverflow.com/a/41119253/217408

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ ComponentOne, ComponentTwo ],
  entryComponents: [ ComponentOne, ComponentTwo ]
})
export class AppModule { 
  ngDoBootstrap(appRef: ApplicationRef) {
    if(document.querySelector('component-one')) {
      appRef.bootstrap(ComponentOne);
    }
    if(document.querySelector('component-two')) {
      appRef.bootstrap(ComponentTwo);
    }
  }
}

https://stackoverflow.com/a/39687157/217408

platformBrowserDynamic([{ provide: SharedService, useValue: sharedService }]).bootstrapModule(AppModule)
platformBrowserDynamic([{ provide: SharedService, useValue: sharedService }]).bootstrapModule(AppModule2)

The former creates a single application (shared zone) which makes it easier to use shared services to communicate. The later creates individual Angular2 applications on the same page.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • This worked great. Could you also tell how to load the second component in the second div when a button is clicked in the first div i.e. the template of the first component. The second div is created dynamically on button click. – Shahrukh Sayyed Jan 05 '17 at 10:41
  • You can inject a service to `AppModule`s constructor and notify `AppModule` about adding another component. You would need to keep a reference to `appRef` passed to `ngDoBootstrap()` and then when the service notifies `AppModule` call `appRef.bootstrap(OtherComponent)`. I have no idea if alling `appRef.bootstrap(...)` after `ngDoBootstrap()` was completed is supposed to work. – Günter Zöchbauer Jan 05 '17 at 10:48