【问题标题】:Angular2 @ViewChild ElementRef offsetHeight always 0Angular2 @ViewChild ElementRef offsetHeight 总是 0
【发布时间】:2017-06-04 16:50:33
【问题描述】:

我正在尝试在我的模板中引用组件的元素,并且高度始终为 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>

这很奇怪,因为该元素渲染良好并占用空间,但即使在几秒钟后单击仍返回 0 的高度。

https://gyazo.com/6504d4f41e6e0072df517082f63fa6ae

【问题讨论】:

  • 我的内容孩子也有同样的问题。
  • 我必须将主机元素设置为显示:块(因此在您的情况下是登录表单的主机元素)。也许这也有帮助

标签: html angular viewchild


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我刚刚在我的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);
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2020-06-12
      • 2019-01-16
      • 2021-07-10
      • 1970-01-01
      • 2015-11-05
      • 2016-08-05
      • 2017-03-18
      • 2022-07-19
      相关资源
      最近更新 更多