Various communication components of a module in Angular 2

I have one component, and I want it to pass data to another, which is in another module. In fact, my app.component is the parent of these child modules. And I want each child module to send some data to app.component . But they are children and parents only in the sense of routing. So they are not really parents and children, I think.

I mean, my temple for app.component as follows:

  <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-left"> <li><a routerLink="link1" routerLinkActive="active">Page1</a></li> <li><a routerLink="link2" routerLinkActive="active">Page2</a></li> <li><a routerLink="link3" routerLinkActive="active">Page3</a></li> <li><a routerLink="link4" routerLinkActive="active">Page4</a></li> </ul> </div> </nav> <div *ngIf="needsSidebar" id="sidebar">some content</div> <div> <router-outlet></router-outlet> </div> 

So app.component does not have a direct connection to these modules and their components. I tried to use Output , but since components from different modules did not work. I have lost what I have to do. I want my "kids" modules to send data to app.module to tell him if they need a sidebar and what content the sidebar should show. How should I do it?

+6
source share
2 answers

It doesn't matter how the modules are connected. It is important if the components are children in the component view. In this case, you can use Angulars binding syntax. In other cases, use the general service. See https://angular.io/docs/ts/latest/cookbook/component-communication.html for details

It is also important where you add the general service as a provider. If you add it to a component, only an instance of that component and its children and descendants share this service instance. If you add the service to @NgModule() providers, one instance will be shared by the entire application (for non-lazy loaded modules).

+6
source

For this scenario, you can look at sharedModule . SharedModule shares the services,pipes & etc that you want to use in different modules / components.

+1
source

All Articles