24

How do I change the body class via the root component?

@Component({ 
   selector: "app", 
   directives: [ROUTER_DIRECTIVES], 
   template: ` 
       <section class="header"> 
           <h1>App</h1>  
           <router-outlet></router-outlet> ` 
}) 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

7 Answers7

23

Here you can simple use the native JavaScript in the Angular2 component to change the class of the <body> tag:-

let body = document.getElementsByTagName('body')[0];
body.classList.remove("className");   //remove the class
body.classList.add("className");   //add the class
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Saurabh
  • 449
  • 4
  • 7
22

One way that doesn't depend on direct DOM manipulation is, to make the <body> tag the app element by using body as selector and use host-binding to update the app elements classes.

@Component({
   selector: 'body',
   host:     {'[class.someClass]':'someField'}
})
export class AppElement implements AfterViewInit {
  someField: bool = false;
  // alternatively to the host parameter in `@Component`
  // @HostBinding('class.someClass') someField: bool = false;

  ngAfterViewInit() {
    someField = true; // set class `someClass` on `<body>`
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
6

Use below code.

 ngOnInit() {
    let body = document.getElementsByTagName('body')[0];
    body.classList.add('body-landing');
  }
  
  
  ngOnDestroy() {
    let body = document.getElementsByTagName('body')[0];
    body.classList.remove("body-landing");
  }
Lakin Mohapatra
  • 1,097
  • 11
  • 22
4

Still looking for a better solution, here is my current workaround:

import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';


@Component({
    selector: 'signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.css',], // Where my custom CSS styles for body element declared
    encapsulation: ViewEncapsulation.None, // That will not encapsulate my CSS styles (layout-full, page-signup) from signup.component.css inside component
})


export class SignupComponent implements OnInit, OnDestroy{

    bodyClasses:string = "layout-full page-signup";

    ngOnInit(): void {
        $('body').addClass(this.bodyClasses);
    }
    ngOnDestroy() { 
        $('body').removeClass(this.bodyClasses);
    }


}
Alex Paramonov
  • 2,630
  • 2
  • 23
  • 27
3

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");
    }
}
Devner
  • 6,825
  • 11
  • 63
  • 104
2

i resove it by use the routeing - like this -add to the root-app component this code :

 this.activeRouter.events.subscribe(
      data => {
        this.className = data.url.split('/').join(' ').trim();
        this.changeBodyClass();
      })

and the body change:

changeBodyClass(){
    if(this.el.nativeElement.parentElement.nodeName === 'BODY'){
       this.el.nativeElement.parentElement.className = this.className ? this.className + '-page' : 'home-page';
    }

you need to inject in the constractor:

constructor(private activeRouter: Router,
              private el: ElementRef)
yanai edri
  • 359
  • 2
  • 4
1
 ngOnInit() {
         let body = document.getElementsByTagName('body')[0];
         body.classList.add('nom_class');                                           
 }

For add one or more classes to the element:

body.classList.add('make', 'me', 'look', 'rad');
William Cauich
  • 151
  • 1
  • 4