【发布时间】: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