I have three components. These are HomeComponent, SignInComponent and AppComponent. My Home Page (HomeComponent) is showing when the application opened. I clicked the "Sign In" button by signin page opens.I want "signin-page" class to body while opening it.
How can I do it?
// AppComponent
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {}
// SignInComponent
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css']
})
export class SignInComponent {}
// HomeComponent
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent { }
// Part of index.html
<body>
<app>
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</app>
</body>
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';
}
}
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
let body = document.getElementsByTagName('body')[0];
body.classList.remove("className"); //remove the class
body.classList.add("className"); //add the class
很简单,您可以这样做将一个类添加到正文中
document.body.classList.add('signin-page');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.