Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the body class via a typescript class (angular2)

Tags:

angular

styles

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

2 Answers

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
like image 78
Saurabh Avatar answered Sep 14 '25 10:09

Saurabh


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>`
  }
}
like image 22
Günter Zöchbauer Avatar answered Sep 14 '25 10:09

Günter Zöchbauer