角度 5 视图子客户端高度、滚动顶部、滚动高度之后均为零



我有一个带有可滚动内容的组件。但是,当我尝试使用 ViewChild 获取角度中可滚动内容的尺寸时,我得到所有值的零,但是如果我使用 jQuery 抓取元素,我会得到正确的值。为什么会这样?我应该如何在 Angular 中获得正确的尺寸?我验证了两者具有相同的元素,但我相信角度可能没有正确的值或元素?在控制台中查看jQuery和Angular似乎具有相同的元素,从css类和html名称来看。

模板:

<div class="container-fluid px-5 py-5 scrolled-contents" style="display:inline-block" #scrolledContents>
  <div class="row">
  ...content
  </div>
</div>

控制器代码:

export class ScrollContainer implements OnInit {
  @ViewChild('scrolledContents') private scrollContainer: ElementRef;
  @HostListener("window:scroll", [])
  onScroll(): void {
    const jQueryelement = $(".scrolled-contents")[0];
    const angularElement = this.scrollContainer.nativeElement;
    // angularElement.clientHeight == 0, angularElement.offsetHeight == 0, angularElement.scrollTop == 0, etc
    // jQueryElement.clientHeight == correctValue, jQueryElement.offsetHeight == correct value, jQueryElement.scrollTop == correctValue 
  }

请帮忙 ?

这是一个有效的 StackBlitz,我似乎无法重现您的问题。

你给出了你的整个代码吗?它是路由组件吗?任何信息都将是有用的。

最新更新