2

I was attempting to create an observable that could be used to conditionally hide the main navigation menu in my app - so, when the current route was the login page, the navigation would be hidden, otherwise it would be shown.

However, i couldn't figure out a simple way to do this. I know that you could inject the ActivatedRoute, which contains observables to monitor the params and the currently activated URL segment, but the observable I need is required on the AppComponent, which sits outside the router outlet.

My eventual solution was to monitor the router itself for navigation events and compose my required observable manually:

/** Returns a boolean observable that indicates, for each route,
 *  if the menu should be displayed or not
 */
isMenuVisible$(): Observable<boolean>{
  let isMenuCurrentlyVisible = !this.router.isActive('login', true);
  return this.router.events
      .filter(e => e instanceof NavigationEnd) //every route change fires multiple events - only care about the route change as a whole
      .map(() => !this.router.isActive('login', true))
      .startWith(isMenuCurrentlyVisible)
  ;
}

However, this use case doesn't seem that strange, so i was wondering if there was an easier way of accomplishing what i wanted?

snorkpete
  • 14,278
  • 3
  • 40
  • 57
  • I don't think there is an easier way. An alternative approach: You could add information about whether the menu should be shown as `data` to the route and enable disable it depending on what data you get from the current route. Similar to http://stackoverflow.com/questions/38644314/changing-the-page-title-using-the-angular-2-new-router/38652281#38652281 but that would even result to more code but perhaps the route configuration would be easier to maintain because id doesn't depend on the route path. – Günter Zöchbauer Sep 07 '16 at 05:44
  • 1
    Thanks @GünterZöchbauer, i might look at using the data - but might not be worth the extra code for this specific app considering that there's only 3 routes that need to be tested against (the login route and the password reset routes) and that list of routes is unlikely to change (hasn't for the last year). But thanks for the option anyway – snorkpete Sep 07 '16 at 13:47
  • I agree. This only pays off for larger number of routes. – Günter Zöchbauer Sep 07 '16 at 13:58

0 Answers0