【问题标题】:How do I change the body class via a typescript class (angular2)如何通过打字稿类(angular2)更改正文类
【发布时间】:2016-04-10 18:02:59
【问题描述】:

如何通过根组件更改 body 类?

@Component({ 
   selector: "app", 
   directives: [ROUTER_DIRECTIVES], 
   template: ` 
       <section class="header"> 
           <h1>App</h1>  
           <router-outlet></router-outlet> ` 
}) 

【问题讨论】:

  • 您想在&lt;body&gt; 标签中添加/删除 CSS 类?
  • 是的,当用户选中复选框时,我想更改页面样式。所以我想改变body标签的类。

标签: styles angular


【解决方案1】:

这里你可以简单地使用Angular2组件中的原生JavaScript来改变&lt;body&gt;标签的类:-

let body = document.getElementsByTagName('body')[0];
body.classList.remove("className");   //remove the class
body.classList.add("className");   //add the class

【讨论】:

  • 仍然在 Angular2 中不起作用,我们将添加一个单独的样式类
  • 这不是一个真正的角度答案
【解决方案2】:

一种不依赖于直接 DOM 操作的方法是,通过使用 body 作为选择器将&lt;body&gt; 标记为应用元素,并使用主机绑定来更新应用元素类。

@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>`
  }
}

【讨论】:

  • 是否也可以在运行时从函数中切换 someField 值?
  • @FerdiEmmen 这就是它应该被使用的方式。
  • 好的,那我怎么用按钮切换班级呢?
  • template: '&lt;button (click)="someField = !someField"&gt;toggle&lt;/button&gt;'
  • 感谢您的回复,但我想我还不够清楚。我创建了一个 plunkr plnkr.co/edit/ra8uK5MoYyenhAPYHpLY?p=preview
【解决方案3】:

使用下面的代码。

 ngOnInit() {
    let body = document.getElementsByTagName('body')[0];
    body.classList.add('body-landing');
  }
  
  
  ngOnDestroy() {
    let body = document.getElementsByTagName('body')[0];
    body.classList.remove("body-landing");
  }

【讨论】:

  • 已有相同的答案,请避免重复
  • 我认为不鼓励直接访问元素属性?
【解决方案4】:

仍在寻找更好的解决方案,这是我目前的解决方法:

import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';


@Component({
    selector: 'signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.css',], // Where my custom CSS styles for body element declared
    encapsulation: ViewEncapsulation.None, // That will not encapsulate my CSS styles (layout-full, page-signup) from signup.component.css inside component
})


export class SignupComponent implements OnInit, OnDestroy{

    bodyClasses:string = "layout-full page-signup";

    ngOnInit(): void {
        $('body').addClass(this.bodyClasses);
    }
    ngOnDestroy() { 
        $('body').removeClass(this.bodyClasses);
    }


}

【讨论】:

  • 如果那是 jquery 更好的解决方案就是使用任何其他答案,没有意义包括整个库
【解决方案5】:

如果只有在特定组件处于活动状态时才需要从正文中添加和删除类,可以按如下方式完成。在我的具体情况下,我只想在用户登陆主页(视图)时添加“landing-page”类,并在用户导航到其他视图时删除该类:

import {Component, OnInit, OnDestroy} from '@angular/core';

export class HomeComponent implements OnInit {

    constructor() {}

    //Add the class to body tag when the View is initialized
    ngOnInit() {
        let body = document.getElementsByTagName('body')[0];
        body.classList.add("landing-page");
    }

    //Remove the class from body tag when the View is destroyed
    ngOnDestroy() {
        let body = document.getElementsByTagName('body')[0];
        body.classList.remove("landing-page");
    }
}

【讨论】:

    【解决方案6】:

    我通过使用路由来解决它 - 像这样 -将此代码添加到根应用程序组件:

     this.activeRouter.events.subscribe(
          data => {
            this.className = data.url.split('/').join(' ').trim();
            this.changeBodyClass();
          })
    

    还有身体变化:

    changeBodyClass(){
        if(this.el.nativeElement.parentElement.nodeName === 'BODY'){
           this.el.nativeElement.parentElement.className = this.className ? this.className + '-page' : 'home-page';
        }
    

    你需要注入构造函数:

    constructor(private activeRouter: Router,
                  private el: ElementRef)
    

    【讨论】:

      【解决方案7】:
       ngOnInit() {
               let body = document.getElementsByTagName('body')[0];
               body.classList.add('nom_class');                                           
       }
      

      为元素添加一个或多个类:

      body.classList.add('make', 'me', 'look', 'rad');
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 1970-01-01
        • 2017-05-21
        • 1970-01-01
        • 2017-02-22
        • 2017-01-06
        • 2019-03-20
        • 1970-01-01
        • 2022-12-07
        相关资源
        最近更新 更多