6

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 this..

index.html

<body [ngClass]="{
  'dashboard site-navbar-small' :isAuthenticated,
  'login-form login-form-second page-login-second' :!isAuthenticated
}">
  <app-root>Loading...</app-root>

login.component.ts

export class LoginComponent {
  @HostBinding('class.login-form.login-form-second.page-login-second')
  siteNavbarSmallClass = false;
  constructor(private auth:Auth){
    this.siteNavbarSmallClass=this.auth.authenticated();
  }
}

app.component.ts

 export class AppComponent {
  @HostBinding('class.dashboard.site-navbar-small')
  dashboardClass = false;
  constructor(private auth:Auth){
      this.dashboardClass=this.auth.authenticated();
  }
}

I am trying to bind ngClass directive to isAuthenticated field.. but I doesnt affected. I heard we are not able to change body element via ts, how can I handle it with anyway ?

TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

3 Answers3

8

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');
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

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>`
  }
}
Devansh
  • 1,277
  • 1
  • 13
  • 19
  • Can you explain what did you do here? Is this a new component with a selector 'body'? or did you change the AppComponent to be the body?? Please add some additional explanations. I want to make this code valid: `` how does you answer make this work? – Gil Epshtain Jun 02 '20 at 10:49
  • @GilEpshtain As it was written 4-years ego, I was learning Angular2. What I remember it that changes the selector to `body` of `AppComponent` and `` this will add your class to the `body` element. Thanks for your concern I also wanted that valid code should be their. – Devansh Jun 02 '20 at 17:12
2

You can also use Renderer2 to modify the body class.

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

or

renderer.removeClass(document.body, "myClass"); 
Adrian Ber
  • 20,474
  • 12
  • 67
  • 117