Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 @ViewChild ElementRef offsetHeight always 0

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

like image 299
Josh Elias Avatar asked Jan 19 '17 20:01

Josh Elias


2 Answers

I just added setTimeout() in my ngAfterViewInit() function like this:

Simple way:

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.

Better way

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);
like image 59
Vala Khosravi Avatar answered Oct 10 '22 02:10

Vala Khosravi


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

like image 29
Bùi Xuân Hải Avatar answered Oct 10 '22 00:10

Bùi Xuân Hải