我一直在尝试保持包含数百行数据的网格的元素的滚动位置。现在它设置为overflow-y: auto。如果我使用路由器转到不同的页面然后返回,我希望滚动条位于相同的位置。我认为使用 ngAfterViewInit 可以解决问题,但不幸的是它不起作用。如果我使用控制台启动设置位置命令,它可以正常工作。我猜问题是在调用 ngAfterViewInit 时行仍在加载但尚未渲染。
@Component({
selector: 'grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.scss']
})
export class GridComponent implements OnInit, OnDestroy {
@Input() rows: Array<Row>;
@Input() someKindOfGridId: string;
localGridConfigValue: ILocalGridConfigValue;
constructor(private configService: ConfigService) { }
ngOnInit() {
this.localGridConfigValue = this.configService.getConfigForCurrentGrid(this.someKindOfGridId);
}
ngAfterViewInit(){
document.getElementById(this.someKindOfGridId).scrollTop = this.localGridConfigValue.gridScrollTopPos;
}
ngOnDestroy() {
this.localGridConfigValue.gridScrollTopPos = document.getElementById(this.someKindOfGridId).scrollTop;
}
}
Run Code Online (Sandbox Code Playgroud)
我仍在学习角度,任何帮助将不胜感激。
问候。
我设法使用@Andresson 的提示解决了这个问题,但 DoCheck 还不够,我使用了 ngAfterViewChecked 代替。重要的是我必须确保设置滚动位置只会触发一次。
@Component({
selector: 'grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.scss']
})
export class GridComponent implements OnInit, OnDestroy {
@Input() rows: Array<Row>;
@Input() someKindOfGridId: string;
localGridConfigValue: ILocalGridConfigValue;
rowsCount: number = 0;
scrolled: boolean = false;
constructor(private configService: ConfigService) { }
ngOnInit() {
this.localGridConfigValue = this.configService.getConfigForCurrentGrid(this.someKindOfGridId);
this.scrolled = false;
}
ngAfterViewChecked() {
let newRowsCount = this.rows.length;
if (newRowsCount <= 0 || !this.rowsCountChanged(newRowsCount) || this.scrolled)
return;
document.getElementById(this.someKindOfGridId).scrollTop = this.localGridConfigValue.gridScrollTopPos;
this.rowsCount = newRowsCount;
this.scrolled = true;
}
private rowsCountChanged(newRowsCount: number): boolean {
return newRowsCount !== this.rowsCount;
}
ngOnDestroy() {
this.localGridConfigValue.gridScrollTopPos = document.getElementById(this.someKindOfGridId).scrollTop;
this.scrolled = false;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22651 次 |
| 最近记录: |