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

1

5

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.

Contradistinction answered 19/3, 2018 at 4:55 Comment(6)
Tried element.offsetHeight; ?Featly
Yes. I am able to set the height and everything. The problem is that I don't get the updated height after the div is re-rendered.Contradistinction
@NimishDavidMathew: check $apply . May be you are missing digest cycle and hence you arent getting updated valueHemichordate
@ShashankVivek Can you elaborate on how to use $apply? I am using Angular 4.Contradistinction
@NimishDavidMathew: You had the wrong tag of "angularjs". Can you share your Angular 4 code so that we can see the actual code. Try tick() function for change detection cycle.Hemichordate
@ShashankVivek Added the code in the question.Contradistinction
C
16

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

Contradistinction answered 22/3, 2018 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.