1

Add or remove class to/from body tag based on the route component in angular 7

for eg.

if path is /login i need to add a class 'abc' to body if path is something i don't add any class to body

user8765332
  • 85
  • 3
  • 9
  • Possible duplicate of [Angular2 add class to body tag](https://stackoverflow.com/questions/43542373/angular2-add-class-to-body-tag) – UncleDave Jan 14 '19 at 10:21
  • Why do you want to do that, because of special layout on login page? In this case you can also use different layouts via different route-components. – J. Knabenschuh Jan 14 '19 at 10:22

1 Answers1

1

You just have to do the following on your component :

constructor(
    @Inject(DOCUMENT) private document: any
) {
    this.document.body.classList.add('abc');
}
Jscti
  • 14,096
  • 4
  • 62
  • 87
  • how do i remove this class when I move to any other component. I don't want to remove it individually in all other components. Is there an easy way – user8765332 Jan 14 '19 at 15:28
  • You use AngularRouter to have a base component that all your childrens will be injected in (see https://angular.io/guide/router#a-crisis-center-with-child-routeshttps://angular.io/guide/router#a-crisis-center-with-child-routes) and in this component you addClass on ngOnInit and you remove it in ngOnDestroy – Jscti Jan 15 '19 at 08:11
  • 1
    @user8765332 `this.document.body.classList.toggle('abc', someCondition);` ([Reference](https://alligator.io/js/classlist/)) – Frank N Feb 20 '20 at 15:38