Last updated on November 20, 2017
Inside the root app component, Inject the Router
and subscribe to route change events and detect the NavigationStart event with the event type instance, its called NavigationStart
.
With the Renderer2
class we can add and remove class to the body as shown below.
import { Component, Renderer2 } from '@angular/core'; import { Router, NavigationStart } from '@angular/router'; import './operators'; /** * This class represents the main application component. */ @Component({ moduleId: module.id, selector: 'ar-app', templateUrl: 'app.component.html', styleUrls: ['app.component.css'], }) export class AppComponent { previousUrl: string; constructor(private renderer: Renderer2, private router: Router) { this.router.events .subscribe((event) => { if (event instanceof NavigationStart) { if (this.previousUrl) { this.renderer.removeClass(document.body, this.previousUrl); } let currentUrlSlug = event.url.slice(1) if (currentUrlSlug) { this.renderer.addClass(document.body, currentUrlSlug); } this.previousUrl = currentUrlSlug; } }); } }