Angular2 add class to body tag

前端 未结 2 1750
误落风尘
误落风尘 2020-11-28 21:02

How can I add a class to the body tag without making the body as the app selector and using host binding?

I tried

2条回答
  •  无人及你
    2020-11-28 21:49

    I would love to comment. But due to missing reputation I write an answer. Well I know two possibilities to solve this issue.

    1. Inject the Global Document. Well it might not be the best practice as I don't know if nativescript etc supports that. But it is at least better than use pure JS.
    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');
      }
    

提交回复
热议问题