Search code examples
kendo-ui-angular2

Setting scroll position on Kendo Angular Grid


When a grid is in a component at one route and the user navigates away and then comes back, the current kendo grid loses its scroll position and starts at the top. Anyone know a way to "remember" the scroll position so it can be set on the grid manually?


Solution

  • Not a great solution, but it works for the time being. Here it is. Inside the component with the grid:

    private _scrollPos: number;
    
    @ViewChild("grid", { read: ElementRef }) gridEl: ElementRef;
    
    constructor(private router: Router) { }
    
    ngOnInit(): void {
        this.router.events.subscribe(e => {
            if (e instanceof NavigationStart) {
                let gridContent = this.getGridContentElement();
                if (gridContent.scrollTop > 0) {
                    this._scrollPos = gridContent.scrollTop;
                }
            }
            else if (e instanceof NavigationEnd) {
                if (this._scrollPos > 0) {
                    let gridContent = this.getGridContentElement();
                    gridContent.scrollTo({ top: this._scrollPos });
                }
            }
        }
    }
    
    private getGridContentElement(): Element {
        let el = this.gridEl.nativeElement as HTMLElement;
        let gridContent = el.getElementsByClassName("k-grid-content").item(0);
        return gridContent;
    }