0

Can you tell me how to get the height of this div content?

i.e. I need it to calculate the dynamic heigh of the content

enter image description here

code

.html

<div class="margin-top-47 margin-horizontal-10" #hello>
//content here
</div>

I have tried like so. But no luck yet. Any clue, please?

.ts

@ViewChild('hello', { static: false }) hello: ElementRef;

  ngAfterViewInit(): void {
   
    const xx = this.hello.nativeElement as HTMLElement;
   
    const contentHeight = xx.clientHeight;//it shows 0

    //const contentHeight = xx.scrollHeight;//it shows 0 too.
    
  }

console.log shows like so:

enter image description here

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • Are you sure the div in question and its content is fully rendered when `ngAfterViewInit` gets called? – Jacopo Sciampi Jul 07 '22 at 15:01
  • @JacopoSciampi Yes, please see the update. – Sampath Jul 07 '22 at 15:07
  • Did you try with `getBoundingClientRect()` ?. [More details](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) – Thierry Falvo Jul 07 '22 at 15:19
  • Is this useful ? https://stackoverflow.com/questions/32438642/clientwidth-and-clientheight-report-zero-while-getboundingclientrect-is-correct – Thierry Falvo Jul 07 '22 at 15:20
  • @ThierryFalvo It shows like so: `bottom: 0 height: 0 left: 0 right: 0 top: 0 width: 0 x: 0 y: 0` – Sampath Jul 07 '22 at 15:22
  • See that you use `{static:false}` **only** if your div is always visible (if it's not under a *ngIf). Check also if you has another variable that was called "hello" – Eliseo Jul 08 '22 at 06:58
  • NOTE: If you only want to change the heigth of one dive you can use directly in .html some like: `[style.height.px]="hello.clientHeight"` – Eliseo Jul 08 '22 at 07:51

2 Answers2

0

Check this out....

@ViewChild('hello', { static: false }) hello: ElementRef|any;

ngAfterViewInit(): void {
   
    const xx = this.hello.nativeElement as HTMLElement;
   
    const contentHeight = xx.clientHeight;
    console.log(contentHeight);


    
  }

check this Html src

enter image description here

check the log

enter image description here

Sampath
  • 63,341
  • 64
  • 307
  • 441
0

I use the Ionic Sheet modal component here. It requires giving a 500ms delay as shown below to give the height.

.html

<div class="margin-top-47 margin-horizontal-10" #sheetModalContent >
 //content here
</div>

.ts

@ViewChild('sheetModalContent ', { static: false }) sheetModalContent : ElementRef;

ngAfterViewInit(): void {
    setTimeout(() => {
      const sheetModalContent = this.sheetModalContent.nativeElement as HTMLElement;
      const sheetModalContentHeight = sheetModalContent.scrollHeight;
      console.log(`sheetModalContentHeight`, sheetModalContentHeight);//438
    }, 500);
  }
Sampath
  • 63,341
  • 64
  • 307
  • 441