Add class to body on Angular2

前端 未结 4 1056
Happy的楠姐
Happy的楠姐 2020-12-10 12:07

I have three components. These are HomeComponent, SignInComponent and AppComponent. My Home Page (HomeComponent) is showing when the application opened. I clicked the \"Sign

相关标签:
4条回答
  • 2020-12-10 12:47

    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
    0 讨论(0)
  • 2020-12-10 12:50

    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';
      }
    }
    
    0 讨论(0)
  • 2020-12-10 12:50

    Simple you can do this to add a class to body

    document.body.classList.add('signin-page');
    
    0 讨论(0)
  • 2020-12-10 13:06
    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.
    0 讨论(0)
提交回复
热议问题