How do I change the body class via the root component?
@Component({
selector: \"app\",
directives: [ROUTER_
In case someone needs to add and remove class from body only when a specific component is active, it can be done as below. In my specific case, I wanted to add the "landing-page" class only when user lands on Home Page (View) and remove that class when user navigates to other views:
import {Component, OnInit, OnDestroy} from '@angular/core';
export class HomeComponent implements OnInit {
constructor() {}
//Add the class to body tag when the View is initialized
ngOnInit() {
let body = document.getElementsByTagName('body')[0];
body.classList.add("landing-page");
}
//Remove the class from body tag when the View is destroyed
ngOnDestroy() {
let body = document.getElementsByTagName('body')[0];
body.classList.remove("landing-page");
}
}