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 Answers
Inject the element itself:
constructor(private elRef: ElementRef){}
access the native elements parent:
ngOnInit() {
console.log(this.elRef.nativeElement.parentElement);
}
-
2It 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 fromChildComponent
? 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
.– JSmithCommented Mar 10, 2022 at 8:47
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')
}
-
closest is NOT supported by internet explorer, so... Commented Feb 8, 2021 at 14:12
-
6
-
1you missed a
nativeElement
this.elRef.nativeElement.closest('view-area-view')
– sandroidCommented Feb 5, 2023 at 19:42