Adding dynamic classes to the angular6 based on route.
import { Router, NavigationStart } from ‘@angular/router’;
import ‘./operators’;
@Component({
moduleId: module.id,
selector: ‘app-root’,
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) {
let arr = this.previousUrl.split(‘/’);
arr.forEach(item=>{
this.renderer.removeClass(document.body, item);
})
}
let currentUrlSlug = event.url.slice(1)
if (currentUrlSlug) {
let arr = currentUrlSlug.split(‘/’);
arr.forEach(item=>{
this.renderer.addClass(document.body, item);
})
}
this.previousUrl = currentUrlSlug;
}
});
}
}