user875139
user875139

Reputation: 1621

Add a class to a specific dom outside of Component in Angular2

I have a component that opens up a modal based on if the a variable called 'isVisible' is True or False. Once the modal is visible, I would like to add a class to the 'body' tag of the page and once it is closed, I'd like to remove the class from the 'body' tag.

Below is a snippet of my code and what I have tried.

import {Component, ElementRef} from '@angular/core';

@Component({
    selector: 'modal',
    template: '<div class="modal_div">
        <div (click)="closeCard()"></div>
        <div class="modal_body">blah</div>
    </div>'
})

export class DailogComponent{
    isVisible: boolean;
    constructor(public element: ElementRef){
        this.isVisible = false;
    }

    OpenModal(){
        this.isVisible = true;
        //add css class to body here which is where I am lost 
       console.log(this.element.nativeElement.parentNode.querySelector('body'));
    }

    closeModal(){
        this.isVisible = false;
        //remove css class to body here which is where I am lost 
       console.log(this.element.nativeElement.parentNode.querySelector('body'));
    }
}

Upvotes: 1

Views: 1187

Answers (1)

Ced
Ced

Reputation: 17337

Someone correct me if this is wrong or an anti pattern in ng.

You can just use javascript for that. If I understood correctly you want to change the class of the body tag. So the body of the page. <body></body>

How do I toggle an element's class in pure JavaScript?

and getElementsByTagName() or yeah query selector as you did, I personally use getElementsByTagName for no good reason other than I'm used to it.

  //don't capitalize function names.
  toggleBodyClass(){
    this.toggleClass(document.getElementsByTagName('body')[0], 'myclass');
  }
  //this function is taken from the Stackoverflow thread posted above.
  toggleClass(ele, class1) {
    let classes = ele.className;
    let regex = new RegExp('\\b' + class1 + '\\b');
    let hasOne = classes.match(regex);
    class1 = class1.replace(/\s+/g, '');
    if (hasOne)
      ele.className = classes.replace(regex, '');
    else
      ele.className = classes + class1;
  }

tested, works

Upvotes: 1

Related Questions