我在 Angular 应用程序中有这个代码
html:
<input type="button" value="Add" (click)="addItems()" />
<div id="messageContainer" style="width:200px; height:300px; overflow-y:scroll;" #scrollMe >
<div *ngFor="let i of items">
{{i}}
</div>
</div>
组件.ts:
items: string[] = [];
count = 20;
@ViewChild('scrollMe') private scrollContainer: ElementRef;
ngOnInit() {
this.addInitialItems();
}
addItems() {
const currentPosition = this.scrollContainer.nativeElement.scrollTop;
this.items.unshift(this.count.toString());
this.count++;
this.scrollContainer.nativeElement.scrollTop = currentPosition;
}
addInitialItems() {
for (let i = 0; i <= this.count - 1; i++) {
this.items.unshift(i.toString());
}
// this is not working
this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
}
最初,messageContainer div 应该填充多个项目,div 滚动到底部,一旦用户单击 Add 按钮,它会将一个项目添加到 messegaes 列表的顶部,并且应该保持滚动位置。
保留滚动位置是通过
const currentPosition = this.scrollContainer.nativeElement.scrollTop;
//add new item
this.scrollContainer.nativeElement.scrollTop = currentPosition;
但是,初始滚动到 div 的底部不起作用,
this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
scrollTop
即使设置后值为0,最初如何让这个滚动到 div 的底部?
最佳答案
@ViewChild 对象在 'ngAfterViewInit' 生命周期钩子(Hook)之前没有完全定义。尝试将您的方法调用移至该钩子(Hook)。
ngAfterViewInit() {
this.addInitialItems();
}
您可能想尝试的其他方法是直接在模板中绑定(bind)到 scrollTop,因此您根本不必访问 nativeElement。
<input type="button" value="Add" (click)="addItems()" />
<div id="messageContainer" style="width:200px; height:300px; overflow-y:scroll;" [scrollTop]="myScrollVariable">
<div *ngFor="let i of items">
{{i}}
</div>
</div>
在您的组件中,您可以简单地编写类似的内容
this.myScrollVariable = currentPosition;
而不是直接修改 DOM 元素。当然,如果您想将滚动初始化为 scrollHeight,您可能仍然需要使用 ViewChild 来访问 nativeElement 并获取该属性(尽管就个人而言,我只会将 scrollTop 初始化为一些荒谬的高数字,例如 99999999,任何大于scrollHeight 将与确切的 scrollHeight 相同)。
如果将方法调用移动到 ngAfterViewInit 不起作用,请尝试在 setTimeout 函数中设置 scrollTop。有时 Angular 更改检测器对于获取对 native DOM 的更改很奇怪,作为一种解决方法,您可以通过超时来逃避常规 Angular 事件循环之外的更改。
setTimeout(()=>{ this.scrollContainer.nativeElement.scrollTop = whatever; },1)
关于html - 设置 nativeElement.scrollTop 不起作用,滚动到 div 的底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270123/