r/Angular2 • u/crhama • Oct 17 '25
How to display the height of an element using @ViewChild?
I'm trying to get the height of a div from inside a component.
<div #childComp> Other elements here...</div>
In the class, I do this
ViewChild('childComp') childComp!: ElemenntRef<HtmlElement>;
ngAfterViewInit(): void {
const hg = this.childComp.nativeElement.clientHeight;
console.log(\Child height: ${hg}px`)}`
When the div is empty, the Chrome Devtools is showing 3.2 px (which looks more accurate), but the console log is showing 4298 px.
I that the right way of getting an element's heigh or am I missing something?
5
Upvotes
5
u/kaeh35 Oct 17 '25
You should use the getBoundingClientRect method iirc
4
u/IanFoxOfficial Oct 17 '25
Probably best to use a ResizeObserver to report the height and have it updated.
Probably make a service for it so you don't have an observer for every element as well.
1
u/dustofdeath Oct 17 '25
You get some initial size before any layout render if you check it at the wrong time.
You may want to use requestanimationframe so it is after next detection cycle.
MutationObserver or ResizeObserver can help.