【问题标题】:Scroll to the bottom of the page after element was added to the DOM - Angular 6将元素添加到 DOM 后滚动到页面底部 - Angular 6
【发布时间】:2019-01-13 19:58:13
【问题描述】:

我有一个表单,我将对象添加到数组中,然后我向用户提供创建对象的预览。

我正在使用 *ngFor 循环数组,并将每个元素添加到屏幕底部。我的目标是在添加每个元素后会自动滚动到页面底部

目前我正在使用 setTimeOut 函数,但我想知道有没有更好的方法?

this.createdAppointments.push(appointmentFormValues);

    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
    }, 1);

【问题讨论】:

  • 为什么还需要超时?您可以创建某种“scrollOnAppearance”指令来实现此逻辑,以执行单一职责和可重复性原则。
  • @bryan60 我创建了一个指令,但页面没有滚动到底部。 import {Directive} from '@angular/core'; @Directive({ // tslint:disable-next-line:directive-selector selector: '[AutoScrollDown]' }) export class AutoScrollDownDirective { constructor() { window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); } }
  • 在 afterViewInit 中而不是在构造函数中执行或添加几毫秒的延迟
  • 太棒了!谢谢@bryan60

标签: angular


【解决方案1】:

您可以在新添加的项目上调用 scrollIntoView 方法,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    相关资源
    最近更新 更多