Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - How to apply the rendered height of a div to another div?

I have two named templates. I want to apply the height of the first one to the second one whenever the contents of the first one change. I can access both of them using ElementRef inside the component. So, when I change the properties bound to the first template, I use the corresponding ElementRef to get its height and apply it to the second template's ElementRef.

Now, the problem is that, after the property change, the height that I get from the ElementRef corresponding to the first template is not the updated height. It returns the height of the div before the property change and re-rendering.

I want to be able to get the actual rendered height after the div is updated. What am I doing wrong?

Update:

The code:

var height = `${this.profile.nativeElement.offsetHeight}px`;
this.renderer.setStyle(this.board.nativeElement, "height", height);
this.renderer.setStyle(
this.board.nativeElement,
"overflow-y",
"scroll"
);

Here profile is the ElementRef corresponding to the first div and board the ElementRef of second one. After property change, I call the function containing the above code. Then the height I get is the old height of the div, that is, before the property change and re-rendering.

like image 233
Nimish David Mathew Avatar asked Dec 10 '22 07:12

Nimish David Mathew


1 Answers

Access the ElementRef corresponding to each div using @ViewChild:

@ViewChild("profile") profile;
@ViewChild("board") board;

Implement AfterViewChecked and do the following in ngAfterViewChecked:

constructor(private renderer: Renderer2) { 
}

ngAfterViewChecked() {
  if (this.profile && this.board) {
    var height = `${this.profile.nativeElement.offsetHeight}px`;
    this.renderer.setStyle(this.board.nativeElement, "height", height);
  }
}

renderer is Renderer2 available in @angular/core

like image 173
Nimish David Mathew Avatar answered May 16 '23 06:05

Nimish David Mathew