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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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; } }); } } |
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
How do you write test for this? Renderer2 seems not to be testable…
I do not have much experience with Angular 2 tests, I have check docs. Let me know if found any solutions