Search code examples
angularhtml-tablescrolltopreal-time-updatesteradata-covalent

How to maintain vertical scroll when updating Angular 5 data table?


I'd like to frequently update my data table (Covalent td-data-table with several ng-template) with new data pulled from a JSON REST API. More rows than will fit on browser so user may need to scroll vertically. But when I update the data in the table it redraws completely i.e. the vertical scroll position resets to the top, tool tips flash, etc..

Hacks to e.g. save/restore the vertical scroll such as below kind of work but they create a lot of visual mess, especially in Firefox.

// save vertical scroll
this.scrollTop = this.tableElt.nativeElement.querySelector('.td-data-table-scrollable').scrollTop;

// update table data here
this.data = newData;

// restore vertical scroll
setImmediate(() => {
    this.tableElt.nativeElement.querySelector('.td-data-table-scrollable').scrollTop = this.scrollTop;
  }
});

How can I cleanly update the data in a table (or any component really) without hacking to reset scroll positions & putting up with a lot of flashing behaviour?

If there is no solution using the Covalent data table, is there another Angular 2+ control that handles this properly?

Animated screen capture of problem: Vertical scroll snaps back when data is updated. Vertical scroll should be maintained across data updates. screencapture


Solution

  • I suggest you switch to angular material and bind it to an observable data source.

    https://material.angular.io/components/table/overview#observable-stream-of-data-arrays

    When the datasource(Observable) is updated with new data it will update the DOM and there will be no need to follow scroll events.

    In case you are worried about the number on items listed on a page supports pagination in a simple way; . https://material.angular.io/components/table/overview#pagination

    SideNote: Switch to angular material as their components are well documented, with examples and sample codes Let me know in case you get stuck.