DragonKnight
DragonKnight

Reputation: 1870

How to pass value from a sibling component to router outlet in angular 6?

app.component.html:

<app-navbar>...router links here</app-navbar>
<app-controller>...contains multiple inputs</app-controller>
<router-outlet>... renders n pages </router-outlet>

How to use the dynamic data in <controller> component (which can change by user) in <router-outlet> child pages? The controller component builds the data which needs to be shared across all pages. Each page renders different form of tables based on controller component data.

I tried eventEmitter and @input @outputs but worked for parents and child not this hierarchy. using service also didn't work for dynamic data. I am not sure what is the benchmark for this kind of requirement.

to achieve this in angular.js I would include controller component into each page component and pass its data via $rootScope and add a $rootScope.$watch if I wanted to see they have changed.

Upvotes: 1

Views: 660

Answers (2)

Baboo
Baboo

Reputation: 4258

Use a service for this. Use it in all the pages that requires the shared data and provide it in the app.component so controller and the render-outlet will shared the same service instance.

In the app component:

@Component({
  ...,
  provide: [SharedDataService],
})
export class AppComponent {
}

and in the children:

constructor(
  sharedDataService : SharedDataService,
) { }

This is how Angular recommends to handle communication between components.

Upvotes: 1

Jaishankar
Jaishankar

Reputation: 168

You can start using subject or Behavior Subject from RX js were you can update your data for multiple component at a single shot please find the few examples

// Behavior Subject

// a is a initial value. if there is a subscription 
// after this, it would get "a" value immediately
let bSubject = new BehaviorSubject("a"); 

bSubject.next("b");

bSubject.subscribe((value) => {
  console.log("Subscription got", value); // Subscription got b, 
                                          // ^ This would not happen 
                                          // for a generic observable 
                                          // or generic subject by default
});

bSubject.next("c"); // Subscription got c
bSubject.next("d"); // Subscription got d

// Regular Subject

let subject = new Subject(); 

subject.next("b");

subject.subscribe((value) => {
  console.log("Subscription got", value); // Subscription wont get 
                                          // anything at this point
});

subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d

Upvotes: 1

Related Questions