Reputation: 2704
I'd like to figure out how tall an element on my page is, and set a spacer div to fit. The "intuitive" thing to do here is use a template reference variable.
<div class="spacer" [style.height.px]="footer.clientHeight"></div>
<div class="footer" #footer></div>
This actually almost works - you can interpolate {{footer.clientHeight}}
into the DOM correctly, except (a) this value doesn't seem to change when the footer changes height - it just stays as the initial value and (b), relatedly, the system then throws an error of type ExpressionChangedAfterItHasBeenCheckedError
which is pretty descriptive although doesn't particularly indicate a fix.
So the question is: is there a decent way to do this? The twist here is that my footer div is conditionally rendered with an ngIf
, which I think is adding to my woes.
I poked at viewChild as well, but that doesn't seem to help a lot - I want an observable that pulls the clientHeight (or some other height measure) out of the element.
Upvotes: 2
Views: 1219
Reputation: 7774
When you use the DOM exclusively, sometimes you are at its mercy in terms of the sequencing of variables and references being created. Based on your description it looks like your spacer is rendering before the #footer
reference is available, then once it becomes available its changing the value of spacer
which has already been checked. I'm guessing when you printed the output of {{footer.clientHeight}}
it was below the footer
element? You could try holding off on rendering the spacer
until the footer has been rendered simply by using *ngIf
.
<div class="spacer" *ngIf="footer" [style.height.px]="footer.clientHeight"></div>
<div class="footer" #footer></div>
Upvotes: 3