ZrSiO4
ZrSiO4

Reputation: 146

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?

Upvotes: 1

Views: 4063

Answers (3)

ZrSiO4
ZrSiO4

Reputation: 146

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;
}

Upvotes: 1

topalkata
topalkata

Reputation: 2098

You can set the Grid skip to the same value it last was. You can check out the persist state examples. The Grids use regular paging, but the same principles apply.

Upvotes: 0

Rod
Rod

Reputation: 353

This is can done by remembering which row was selected, saving the id of the row, and then setting the grid property [selectedKeys]="id" when the user navigates back.

For example if the data for the grid was based on product data then save last viewed row id (ProductID). When the user navigates back to grid, you can push the ProductID you saved to an array that is bound on the grid. This will make the row selected, to scroll to the row you can use the class k-state-selected and scrollIntoView to scroll the row into view.

This is a basic implementation, but should give you a enough to go on. I created a Stackblitz example so you can see how to implement this. Make sure to configure the grid with kendoGridSelectBy and selectedKeys. The kendoGridSelectBy should match the id that you push to the array. In the example I created it was ProductID.

Upvotes: 0

Related Questions