0
votes

I am building my web application using angular 6. I have some common component which is common on all routes. For example I have a filter component which is common on all route. Now when user select a filter a click on find this filter data should be passed to different component on same route and then result should be display. PFB my angular's app structure : App.component.html :

<filter (messageToDash)="receiveMessage($event)"></filter>
<router-outlet></router-outlet>

For dash route I have dash component. PFB is code for dash.component.html :

<dashboard></dashboard>

Filter.component.html

<button (click)="somemethod()"></button>

So when user click on button, I want to want to pass some variable to the dashboard component. I also tried using service component and subscribe it into dashboard's ngOnInit() variable, but its not working.

2
Have you ever heard of outputs ? They allow a component to send an event to its parent. - user4676340
but I want to send data to the component which will be rendered by <router-outlet> - user2560457
So dashboard is in the router outlet, but the filter isn't ? - user4676340
yes. I have done in that way so that filter will be shown on all the route - user2560457
Hi @user2560457 use shared service stackoverflow.com/questions/40468172/… - yala ramesh

2 Answers

0
votes

Create a service and give it as reference at the parent Level and on (click) of the the button pass the filter data to the function with return type observable and in component subscribe to the result of the function. Since ngOnInit lifecycle is initialized only at the beginning of the page load, It may not be of much help.

0
votes

I too had stuck in the same problem a few months back, the best solution i got at that time was using LocalStorageService For Example:

import { LocalStorageService } from 'ngx-webstorage';

constructor(private session: LocalStorageService)
{
 //works at the begining of the module before OnInit 
}

some_function()
{
    this.session.store('key_name',yourData);
}

Now in another component just import LocalStorageService and create a obj for it and then:

some_function()
{
    this.your_variable = this.session.retrieve('key_name');
}

Note: the key_name for storing and retrieving must be same. hope this helps.