如何通过typescript类更改body类(angular2)

21 styles angular

如何通过根组件更改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>通过使用bodyas作为选择器使标记成为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)


Lak*_*tra 6

使用下面的代码。

 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)

  • aleady 相同的答案可用请避免重复 (2认同)