Skip to content Skip to sidebar Skip to footer

How To Get The Dimension Of Dynamic Rendered Element In Angular

just imagine: 1. in component.html, you have

{{text}}

Solution 1:

In most cases, you don't need to set the height of the div container in code. It automatically adjusts to its content and can be fine-tuned with CSS style attributes.

But if you want to do some special calculations with the paragraph height to set the height of the div, you can do it with data binding (using the element.offsetHeight property in the calculations):

<div [style.height.px]="calculateDivHeight(paragraph)"><p #paragraph>{{text}}</p><div><button (click)="changeText()">changeText</button>
public calculateDivHeight(paragraph: HTMLElement): number {
    return doSomeProcessing(paragraph.offsetHeight);
}

Your current code could also work if you force change detection (see this answer) just after changing the paragraph content:

import { ApplicationRef } from'@angular/core';

constructor(private applicationRef: ApplicationRef, ...) {
  ...
}

changeText() {
  this.text = 'blablablabla.....';
  this.applicationRef.tick();
  let divEl = this.el.nativeElement.querySelector('#myDiv');
  ...
}

Solution 2:

It returns the previous values because it takes time for the browser to compute the new style.

The RequestAnimationFrame API is what you are looking for.

Once you've set the new text, use the RequestAnimationFrameAPI, it's a callback triggered once the browser is ready, basically when its render queue is empty.

this.text = "blablablabla...."window.requestAnimationFrame(() => {
  // access the new css values here
})

Post a Comment for "How To Get The Dimension Of Dynamic Rendered Element In Angular"