K.Rice K.Rice - 1 month ago 31
TypeScript Question

Different module components communication in Angular 2

I have One component and I want it to pass data to another one which is in another module. Actually my

app.component
is a parent of these children modules. And I want each child module to send some data to
app.component
. But they are children and parent only in a sence of routing. So they aren't actually parents and children, I guess.

I mean, my templet for
app.component
looks like this:

<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
has no direct connection with these modules and theirs components. I tried to use
Output
but since components are from different modules it failed. I'm lost in what should I do. I want my "children" modules to send data to up the
app.module
to tell it if they needs a sidebar and which content should sidebar show. How can I do it?

Answer

It doesn't matter how the modules are related. What matters is, if the components are children in a components view. In this case you can use Angulars binding syntax. In other cases use a shared service. For details see https://angular.io/docs/ts/latest/cookbook/component-communication.html

What also matters is, where you add a shared service as provider. If you add it to a component, only an instance of this component and its children and descendants share this service instance. If you add a service to providers of @NgModule() a single instance is shared with the whole application (for non-lazy loaded modules).