Add class to body on Angular2

2020-02-05 12:24发布

问题:

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>

回答1:

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';
  }
}


回答2:

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


回答3:

  1. 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
  1. I'll prefer answer given by @Yurzui if the whole frontend is in Angular.


回答4:

Simple you can do this to add a class to body

document.body.classList.add('signin-page');