40

Just like in the question - I have a child component, and I would like to know what is the width of the parent element. How can I do that?

2

2 Answers 2

59

Inject the element itself:

constructor(private elRef: ElementRef){}

access the native elements parent:

ngOnInit() {
  console.log(this.elRef.nativeElement.parentElement);
}
3
  • 2
    It will work but it's not a good practice to access the native elements directly. Commented Jul 22, 2016 at 15:34
  • 2
    @BenRichards. Suppose you have two components like this: <parent><div><child></child></div></parent>. How would you get parent's DOM element from ChildComponent? I know I could easily get `ParentComponent˙instance inside child by simply adding it as a constructor parameter, but I don't know how to get the actual element? Commented Feb 15, 2018 at 20:43
  • I've tried this but it doesn't retrieve the computed parent style.
    – JSmith
    Commented Mar 10, 2022 at 8:47
9

You can access closest parent DOM element by looking up with this.elRef.closest and some selector that matches that parent

constructor(private elRef: ElementRef){}

ngOnInit() {
   const parentElement = this.elRef.closest('.parent-element-class')
}
3
  • closest is NOT supported by internet explorer, so... Commented Feb 8, 2021 at 14:12
  • 6
    internet explorer is obsolete Commented Jan 2, 2023 at 10:08
  • 1
    you missed a nativeElement this.elRef.nativeElement.closest('view-area-view')
    – sandroid
    Commented Feb 5, 2023 at 19:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.