简体   繁体   English

将类添加到Angular2上

[英]Add class to body on Angular2

I have three components. 我有三个组成部分。 These are HomeComponent, SignInComponent and AppComponent. 它们是HomeComponent,SignInComponent和AppComponent。 My Home Page (HomeComponent) is showing when the application opened. 打开应用程序时显示我的主页(HomeComponent)。 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 您可以将根选择器更改为body ,然后使用HostBinding装饰器

@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> ). Angular2没有提供任何内置方法来修改根组件之外的DOM元素( <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 也可以看看

  1. If part of your application is in Angular, then you can do this: 如果应用程序的一部分位于Angular中,则可以执行以下操作:
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. 如果整个前端都在Angular中,我希望使用@Yurzui给出的答案。

很简单,您可以这样做将一个类添加到正文中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM