Angular2 @ViewChild ElementRef offsetHeight 始终为 0

Angular2 @ViewChild ElementRef offsetHeight always 0

我试图在我的模板中引用组件的元素,但高度始终为 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);
  }
}

模板

<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>

这很奇怪,因为该元素渲染良好并占用 space 但即使在几秒钟后点击仍然 returns 高度为 0。

https://gyazo.com/6504d4f41e6e0072df517082f63fa6ae

您可以为组件设置 :host { display: block },使其具有高度。默认值为 display: inline。如果您保留默认值,宽度和高度将为 0

我刚刚在 ngAfterViewInit() 函数中添加了 setTimeout(),如下所示:

简单方法:

setTimeout(() => {
  // Do what you want here
  console.log(this.myElement.nativeElement.offsetHeight);
}, _timeout); // Mine worked even with _timeout = 1

并且输出不再为零。

更好的方法

100% 有效的方法是:

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);