I would love to comment. But due to missing reputation I write an answer. Well I know two possibilities to solve this issue.
constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit(){ this.document.body.classList.add('test'); }
Well and perhaps even better. You could inject the renderer or renderer 2 (on NG4) and add the class with the renderer.
export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer) { this.renderer.setElementClass(document.body, 'modal-open', true); } ngOnDestroy() { this.renderer.setElementClass(document.body, 'modal-open', false); }
EDIT FOR ANGULAR4:
import { Component, OnDestroy, Renderer2 } from '@angular/core'; export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer2) { this.renderer.addClass(document.body, 'modal-open'); } ngOnDestroy() { this.renderer.removeClass(document.body, 'modal-open'); }
I think the best way to do it is a combination of both approaches by DaniS above: Using the renderer to actually set / remove the class, but also using the document injector, so it is not strongly dependant on the window.document
but that can be replaced dynamically (e.g. when rendering server-side). So the whole code would look like this:
import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit, Renderer2 } from '@angular/core';
@Component({ /* ... */ })
export class MyModalComponent implements OnInit, OnDestroy {
constructor (
@Inject(DOCUMENT) private document: Document,
private renderer: Renderer2,
) { }
ngOnInit(): void {
this.renderer.addClass(this.document.body, 'embedded-body');
}
ngOnDestroy(): void {
this.renderer.removeClass(this.document.body, 'embedded-body');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With