Search code examples
htmlangularviewchild

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


Solution

  • 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