Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - Add class to body on Angular2

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...