I'm trying to reference a component's element in my template and the height is always 0.
export class LoginComponent {
  @ViewChild("loginForm", {read: ElementRef})
  loginForm;
  constructor() {}
  ngAfterViewInit() {
    console.log("form height: ", this.loginForm.nativeElement.offsetHeight);
  }
  click() {
    console.log("form height: ", this.loginForm.nativeElement.offsetHeight);
  }
}
Template
<div class="modal-content"
    [style.height.px]="contentHeight">
  <login-form #loginForm
    (click)="click()"
    [class.active]="currentForm === 'login'">
  </login-form>
  <register-form
    [class.active]="currentForm === 'register'">
  </register-form>
  <div #registerSuccess class="register-success"
    [class.active]="currentForm === 'registerSuccess'">
    Thank you for registering
  </div>
</div>
It's odd because the element is rendering fine and takes up space but even clicking after a few seconds still returns a height of 0.
https://gyazo.com/6504d4f41e6e0072df517082f63fa6ae
I just added setTimeout() in my ngAfterViewInit() function like this:
setTimeout(() => {
  // Do what you want here
  console.log(this.myElement.nativeElement.offsetHeight);
}, _timeout); // Mine worked even with _timeout = 1
And the output was not zero any-more.
And 100 percent way that works is:
let offsetHeight = 0;
const refreshInterval = setInterval(() => {
  if (offsetHeight === 0) {
    offsetHeight = this.giftImage.nativeElement.offsetHeight;
    // Do what you want here
    console.log(this.giftImage.nativeElement.offsetHeight);
  } else {
    clearInterval(refreshInterval);
  }
}, 10);
                        You can set :host { display: block } for the component so it will have height. Default is display: inline. If you leave it default, width and height will be 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With