How do I change the body class via a typescript class (angular2)

前端 未结 7 1843
失恋的感觉
失恋的感觉 2020-12-14 02:04

How do I change the body class via the root component?

@Component({ 
   selector: \"app\", 
   directives: [ROUTER_         


        
7条回答
  •  离开以前
    2020-12-14 02:56

    In case someone needs to add and remove class from body only when a specific component is active, it can be done as below. In my specific case, I wanted to add the "landing-page" class only when user lands on Home Page (View) and remove that class when user navigates to other views:

    import {Component, OnInit, OnDestroy} from '@angular/core';
    
    export class HomeComponent implements OnInit {
    
        constructor() {}
    
        //Add the class to body tag when the View is initialized
        ngOnInit() {
            let body = document.getElementsByTagName('body')[0];
            body.classList.add("landing-page");
        }
    
        //Remove the class from body tag when the View is destroyed
        ngOnDestroy() {
            let body = document.getElementsByTagName('body')[0];
            body.classList.remove("landing-page");
        }
    }
    

提交回复
热议问题