Angular 2+: How to access active route outside router-outlet

Badis Merabet picture Badis Merabet · Apr 3, 2018 · Viewed 8.7k times · Source

I have an Angular 5 application.

I have the following code in my app component.

I want to hide navbar and topbar for particular routes.

Is it possible to get currently activated route in app.component.ts ? if so, How ?

If not possible, is there any solution to resolve this ( using guards or whatever else ... )?

enter image description here

Also keep in mind that it should be reactive. when i switch to another route sidebar and navbar should show again.

Answer

Tomasz Kula picture Tomasz Kula · Apr 3, 2018

Try this:

in app.component.ts

import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
  showSidebar$: Observable<boolean>;
  private defaultShowSidebar = true;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
  ) {
    this.showSidebar$ = this.router.events.pipe(
      filter(e => e instanceof NavigationEnd),
      map(() => activatedRoute),
      map(route => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;
      }),
      mergeMap(route => route.data),
      map(data => data.hasOwnProperty('showSidebar') ? data.showSidebar : this.defaultShowSidebar),
    )
  }

app.component.html

<aside *ngIf="showSidebar$ | async">Sidebar here</aside>

<router-outlet></router-outlet>

<a routerLink="/without-sidebar">Without sidebar</a>
<a routerLink="/with-sidebar">With sidebar</a>
<a routerLink="/without-data">Without data.showSidebar</a>

app routes

RouterModule.forRoot([
  { path: 'with-sidebar', component: WithSidebarComponent, data: { showSidebar: true } },
  { path: 'without-sidebar', component: WithoutSidebarComponent, data: { showSidebar: false } },
  { path: 'without-data', component: WithoutDataComponent },
])

You can modify it as you please.

Live demo