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

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


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 classbody.classList.add("className");   //add the class


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


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