angularangular6elementref

Alternative of document.getElementsByTagName('body') in angular 2/5/6


I want to get the 'body' element form the other child component.
How can I get the body element form the child component?
As I want to append and remove the class to body form child component.


Solution

  • I can suggest a workaround where you can traverse back until you get body element. And you could use Renderer2 so that code can work smoothely with server side rendering as well.

    getParentNode (node) {
         //make sure you inject Render2 inside constructor.
         return this.renderer.parentNode(node);
    }
    
    getBodyElement (element) {
        let currentElement = element;
        // below can be optimised to have single `getParentNode` method call.
        while(this.getParentNode(currentElement)&& this.getParentNode(currentElement).nodeName != 'HTML'){
          currentElement = this.getParentNode(currentElement)
        }
        return currentElement
    }
    
    ngOnit() {
       let bodyElement = this.getBodyElement(this.elementRef.nativeElement)
    }