Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 将nativeElement.scrollTop设置为滚动到div底部不起作用_Html_Angular - Fatal编程技术网

Html 将nativeElement.scrollTop设置为滚动到div底部不起作用

Html 将nativeElement.scrollTop设置为滚动到div底部不起作用,html,angular,Html,Angular,我在角度应用程序中有这个代码 html: 但是,初始滚动到div底部不起作用 this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight; scrollTop即使在设置后,其值也为0, 如何最初将其滚动到div的底部?@ViewChild对象在“ngAfterViewInit”生命周期挂钩之前没有完全定义。尝试将方法调用移动到该挂钩 ngAfterViewInit(

我在角度应用程序中有这个代码

html:

但是,初始滚动到div底部不起作用

this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
scrollTop
即使在设置后,其值也为0,
如何最初将其滚动到div的底部?

@ViewChild对象在“ngAfterViewInit”生命周期挂钩之前没有完全定义。尝试将方法调用移动到该挂钩

ngAfterViewInit() {
   this.addInitialItems();
}
您可能需要尝试的其他方法是直接在模板中绑定到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>
而不是直接修改DOM元素。当然,如果您想将滚动条初始化为scrollHeight,您可能仍然需要使用ViewChild访问nativeElement并获取该属性(尽管就个人而言,我只是将scrollTop初始化为某个高得离谱的数字,如99999999,任何大于scrollHeight的值都将与精确的scrollHeight相同)

如果将方法调用移动到ngAfterViewInit不起作用,请尝试在setTimeout函数中设置scrollTop。有时,角度变化检测器在获取对本机DOM的变化时很奇怪,作为一种解决方法,您可以在常规角度事件循环之外通过超时来逃避变化

setTimeout(()=>{ this.scrollContainer.nativeElement.scrollTop = whatever; },1)

不需要设置超时。只需在ngAfterViewInit中设置scrollTop的一部分。在ngOnInit/构造函数中设置初始模型值。您很可能是对的,但某些DOM属性/方法在角度上是芬尼基的,有时我必须将它们放入超时状态,以便它们能够一致地更改(.focus())
ngAfterViewInit() {
   this.addInitialItems();
}
<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;
setTimeout(()=>{ this.scrollContainer.nativeElement.scrollTop = whatever; },1)