Modifying <body> css classes in Angular

a simple Solution for modifying the css <class>es of the <body> element in an angular app.

Modifying the css <class>-es on the <body> element is not straight forward. The <body> element is by default the parent of the angular app. It is not in a component template we can easily modify:

<!doctype html>
<html lang="en">
<head>
  <!-- ... -->
</head>
<body>
  <app-root></app-root>
</body>

One solution would be to move it into the root template. Another solution is to access the <body> element by injecting the Document and then using a Renderer2 to modify it:

import {Component, Inject, Renderer2} from '@angular/core';
import {DOCUMENT} from "@angular/common";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private renderer: Renderer2
  ) {}


  showMenu (event: Event) {
    this.renderer.addClass(this.document.body, 'is-menu-visible');
  }

  hideMenu () {
    this.renderer.removeClass(this.document.body, 'is-menu-visible');
  }

}

That’s it.