1

I have a toolbar component aligned above a router outlet. The router outlet has various components like table and chart.

Am able to subscribe to route params in any of the components that are displayed using a router outlet.

I want to access route params from toolbar component which is not part of outlet. (capture current path to show name of route on toolbar)

Main component :

  <app-toolbar> </app-toolbar>
  <router-outlet> </router-outlet> // shows either a table or chart component

toolbar component:

 export class ToolbarComponent {
   constructor(private route: ActivatedRoute) {
      this.route.subscriber(params => 
          { console.log(params) //param is empty }
   }
 }

Table component:

 export class TableComponent{
       constructor(private route: ActivatedRoute) {
          this.route.subscriber(params => 
              { console.log(params) //param has data }
       }
     }
Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39

3 Answers3

1

You need to use route.firstChild or route.children to achieve it, in the same manner that using params.

Kraken
  • 1,905
  • 12
  • 22
1

In your MainComponent where the <app-toolbar> lies you can add:

path$: Observable<String>;

constructor( private router: Router ) {
  this.path$ = this.router.events.pipe(
    filter(event => event instanceof RoutesRecognized),
    map((event: RoutesRecognized) => {
      return event.state.root.firstChild.url.join('/');
    }));
}

And then in the html template, you can write something like:

<app-toolbar>{{ path$ | async }}</app-toolbar>

This was inspired by the second approach in https://stackoverflow.com/a/46697826/9423231

frido
  • 13,065
  • 5
  • 42
  • 56
0

Modify your toolbar component as

toolbar component:

    this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        r.params.subscribe((params) => {
          this.healthStatus(params);
        });
      }
    });
Bensam
  • 1