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> `
})
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
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>`
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With