Home » Featured, Headline, Mobile Development, Software Development

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

28 June 2017 No Comment

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!

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
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