How do I change the body class via a typescript class (angular2)
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"); }