how to change class of body in angular2&typescript project

前端 未结 3 342
温柔的废话
温柔的废话 2021-01-19 22:55

I have diffirent classes for login page and other pages in application so after user logged in I need to change class of body element. Here how I am trying to accomplish thi

相关标签:
3条回答
  • 2021-01-19 23:14

    You can also use Renderer2 to modify the body class.

    renderer.addClass(document.body, "myClass"); 
    

    or

    renderer.removeClass(document.body, "myClass"); 
    
    0 讨论(0)
  • 2021-01-19 23:18

    One way is to use make the <body> tag the app element by using body as selector and use host-binding to update the app elements classes.

    @Component({
       selector: 'body',
       host:     {'[class.someClass]':'someField'}
    })
    export class AppComponent 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>`
      }
    }
    
    0 讨论(0)
  • 2021-01-19 23:36

    Bindings outside <app-root> are not supported.

    What you can do is to use selector: 'body' in you AppComponent and

    @HostBinding('class.dashboard')
    dashboardClass = false;
    
    @HostBinding('class.site-navbar-small')
    siteNavbarSmallClass = false;
    
    ...
    

    and then set the properties to true to get the classes added.

    or just

    document.body.classList.add('dashboard');
    
    0 讨论(0)
提交回复
热议问题