Reputation: 609
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?
Upvotes: 8
Views: 12479
Reputation: 1275
I have had the same problem and tried @Input()
, but it didn't work for me (the @Input()
component reference being always undefined
), probably because of unrelated components. Like this article suggests, shared service is probably the best approach for communicating components in different modules: https://www.pluralsight.com/guides/communicating-across-components-using-services
I am pretty new to Angular and have spent almost 2 hours trying to find any easier way, but then I have set up a service in minutes.
Upvotes: 0
Reputation: 55443
For this scenario, you can have a look at sharedModule. SharedModule shares services,pipes & etc
that you want to avail in different modules/components.
Upvotes: 1
Reputation: 657466
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).
Upvotes: 7