Skip to content

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

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.

angular add dynamic class body based route

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

  }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments