【问题标题】:Angular nativeElement.scrollTop has weird behaviorAngular nativeElement.scrollTop 有奇怪的行为
【发布时间】:2020-04-20 04:13:51
【问题描述】:

你能告诉我为什么this.myScrollContainer.nativeElement.scrollTop 没有得到这个this.myScrollContainer.nativeElement.scrollHeight 的赋值吗?这里发生了什么?

.ts

 @ViewChild('scrollMe', { static: false }) private myScrollContainer: ElementRef;

  scrollToBottom(): void {
     this.myScrollContainer.nativeElement.scrollTop =  this.myScrollContainer.nativeElement.scrollHeight;
   }

.html

<div class="row2" #scrollMe>
      <ion-row>
        <ion-col>
          <app-school></app-school>
        </ion-col>
      </ion-row>
    </div>

.scss

.content {
    ion-grid {
        display: flex;
        flex-direction: column;
        height: 100% !important;
    }

    .row1 {
        flex: 2 !important;
    }

    .row2 {
        flex: 5 !important;
        overflow: scroll !important;
    }
}

Gif - 点击在大屏幕上查看

【问题讨论】:

  • 我们可以看看你如何以及在哪里打电话给scrollToBottom吗?
  • @ConnorsFan 请参见上面 gif 中的 161 行。
  • 我的建议:在调用scrollToBottom()之前调用ChangeDetectorRef.detectChanges()更新视图。
  • @ConnorsFan 这对组件来说是不必要的开销,因为它将重新运行整个组件的更改检测。但是setTimeout()在这里效率更高。

标签: javascript html angular typescript ionic4


【解决方案1】:

在访问原生 DOM 元素时,这似乎是 Angular 的一个错误。我已经完成了下面的操作,现在工作得很好。即使用setTimeout()

scrollToBottom(): void {
   setTimeout(() => { this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; }, 1);
  }

【讨论】:

    猜你喜欢
    • 2017-01-27
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多