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.
Asked
Active
Viewed 1,645 times
3

Shubham Ghormade
- 215
- 4
- 16
1 Answers
3
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)
}

Pankaj Parkar
- 134,766
- 23
- 234
- 299