一个可能的解决方法是,在调用 detectChanges() 函数之前,将当前的滚动位置存储在变量中,并在函数执行后使用 scrollTo() 函数将滚动位置还原。示例如下:
import { Component, ElementRef, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
private scrollPosition: number = 0;
constructor(private elementRef: ElementRef, private cdRef: ChangeDetectorRef) {}
private saveScrollPosition() {
this.scrollPosition = this.elementRef.nativeElement.scrollTop;
}
private restoreScrollPosition() {
this.elementRef.nativeElement.scrollTop = this.scrollPosition;
}
public doSomething() {
this.saveScrollPosition();
this.cdRef.detectChanges();
this.restoreScrollPosition();
}
}
在这个例子中,我们使用 ElementRef 和 ChangeDetectorRef 来获取元素和 change detection 引用。saveScrollPosition() 函数将当前滚动位置存储在 scrollPosition 变量中,而 restoreScrollPosition() 函数将滚动位置恢复为存储在该变量中的位置。在 doSomething() 方法中,我们保存当前的滚动位置,然后调用 detectChanges() 函数,最后恢复滚动位置。
值得注意的是,scrollTo() 函数可能无法与某些浏览器(例如 IE 11)一起使用。在这种情况下,您可以尝试使用 scrollTop 属性来获取和设置滚动位置。