Angular2 add class to body tag

前端 未结 2 1746
误落风尘
误落风尘 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:54

    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');
        }
    }
    

提交回复
热议问题