0

I need to access a Params variable sent to a child component in the parent component.

I have the following structure:

Routing: (excerpt)

  {
      path: 'song',
      component: SongExerciseComponent,
      children: [
          {
              path: 'reading/:id',
              component: SongReadingComponent,
          }
      ]
  }

The parent component is just a template holding navigation links. I can access the :id var in the child component like so:

  ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      if (params['id'] !== undefined) {
        let id = +params['id'];

Now I need the same variable in the parent component to be used in the parent template.

Which is the most effective way to do this? Sharing a service? https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service

Cruclax
  • 394
  • 3
  • 13
  • 1
    Outputs are fine but they are cumbersome if data should be passed through multiple levels of component hierarchy. A shared service looks like a good match for this case (navigation) to me. A service itself can be an observable or EventEmitter, similarly to output's event emitter. – Estus Flask Sep 15 '16 at 00:16

1 Answers1

1

You could create a shared service or use Ngrx store, inspired by Redux for Angular2.

There you can read about it - https://gist.github.com/btroncone/a6e4347326749f938510

The advantage of this solution is that you can subscribe changes and react on them. Also, data is immutable so you will not change something by mistake. If it is not important for you, just use service.

Kamil Myśliwiec
  • 8,548
  • 2
  • 34
  • 33
  • Interesting. Didn't know about Ngrx. However I was trying Angular2 to avoid things like Redux, but it seems Angular2 is not there yet - if it will ever be. – Cruclax Sep 15 '16 at 16:17