Add class to body on Angular2
- If part of your application is in Angular, then you can do this:
let body = document.getElementsByTagName('body')[0];
body.classList.remove("className"); //remove the class
body.classList.add("className"); //add the class
- I'll prefer answer given by @Yurzui if the whole frontend is in Angular.
Angular2 doesn't provide any built in way to modify DOM elements outside the root component (except the <title>
).
querySelector('body').classList.add('signin-page');
querySelector('body').classList.remove('signin-page');
or
@Component(
selector: 'body',
templateUrl: 'app_element.html'
)
class AppElement {
@HostBinding('class.fixed')
bool isFixed = true;
}
See also
- How do I add a class to a given element?
- Angular 2.x bind class on body tag
You can change your root selector to body
and then use HostBinding
decorator
@Component({
selector: 'body',
template: `<child></child>`
})
export class AppComponent {
@HostBinding('class') public cssClass = 'class1';
}
@Component({
selector: 'child',
template: `<button (click)="setClass()">Set class</button>`
})
export class ChildComponent {
constructor(private rootComp: AppComponent) { }
setClass() {
this.rootComp.cssClass = 'class2';
}
}