Posted by Arjun on Monday 7th August 2017

Angular 4 - Add dynamic class to the body based on route.

Route Angular Dynamic Class

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.

[caption id="attachment_5349" align="aligncenter" width="700"]angular add dynamic class body based route[/caption]

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;
        }
      });

  }
}