Angular 4 – Adding custom classes to document body depending on a component

Sometimes the app that is being developed requires different classes on body of html document for styling each route or page.
This can be achieved using the following snippet below.

Login Component

... // other code above
export class LoginComponent implements OnInit, OnDestroy {
 ngOnInit(): void {
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('auth');
  }

  ngOnDestroy(): void {
    const body = document.getElementsByTagName('body')[0];
    body.classList.remove('auth');
  }
... // other code below

Dashboard Component

... // other code above
export class DashboardComponent implements OnInit, OnDestroy {
 ngOnInit(): void {
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('dashboard');
  }

  ngOnDestroy(): void {
    const body = document.getElementsByTagName('body')[0];
    body.classList.remove('dashboard');
  }
... // other code below

Now that the body has classes depending on the route or page component, this makes it easier to style the entire page.

Hope this is beneficial to the readers!

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image