如何通过根组件更改body类?
@Component({
selector: "app",
directives: [ROUTER_DIRECTIVES],
template: `
<section class="header">
<h1>App</h1>
<router-outlet></router-outlet> `
})
Run Code Online (Sandbox Code Playgroud)
小智 22
在这里,您可以简单地使用Angular2组件中的本机JavaScript来更改<body>
标记的类: -
let body = document.getElementsByTagName('body')[0];
body.classList.remove("className"); //remove the class
body.classList.add("className"); //add the class
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 20
一种不依赖于直接DOM操作的方法是,<body>
通过使用body
as作为选择器使标记成为app元素,并使用host-binding来更新app元素类.
@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>`
}
}
Run Code Online (Sandbox Code Playgroud)
使用下面的代码。
ngOnInit() {
let body = document.getElementsByTagName('body')[0];
body.classList.add('body-landing');
}
ngOnDestroy() {
let body = document.getElementsByTagName('body')[0];
body.classList.remove("body-landing");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43946 次 |
最近记录: |