Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeNG table lazy loading not working properly on setting the property first

We are using PrimeNG <p-table> component with virtualScroll = true & lazy = true. But it is not working in the following scenario.

Assume there are 100 records in total and the limit is 10. The user scrolls and sees an item at the offset 50 and he clicks the item and taken to the detail page of that item. Now when the user clicks browser back button I need to bring him back to the same page he was looking in <p-table>, to do that I am setting the property [first] = 50 and it is showing the correct page but when I scroll the event that is emitted contains offset 10 instead of 60, why is that?

like image 886
wolverine Avatar asked Oct 31 '25 10:10

wolverine


1 Answers

When you use [first]="50" you are cutting your data out of first 50 elements. I would suggest to instead track table scrollTop offset and store it in, for example, local storage or some other service. Then when you get back to table view just restore scrollTop to table scrolling body.

Here is some ugly example of how to do it (scroll to some offset and trigger page reload)

ngAfterViewInit() {
  const scrollableBody = this.table.containerViewChild.nativeElement.getElementsByClassName('ui-table-scrollable-body')[0];
  // listen for scrollTop changes
  scrollableBody.onscroll = (x) => {
    localStorage.setItem('scrollTop', scrollableBody.scrollTop);
  }
}

loadItemsLazy(event: any) {
  // immitated lazy data load
  setTimeout(() => {
    if (this.datasource) {
      this.items = this.datasource.slice(event.first, (event.first + event.rows));
    }
    // we need change scrollableBody.scrollTop
    // check some condition for doing it after returning from edit or something
    if (this.restoreOffset) {
      setTimeout(() => {
        const scrollableBody = this.table.containerViewChild.nativeElement.getElementsByClassName('ui-table-scrollable-body')[0];
        // restore last known offset
        scrollableBody.scrollTop = Number.parseInt(localStorage.getItem('scrollTop')) || 0;
      });
    }
  }, 2000); // some random data load time
}
like image 122
Xesenix Avatar answered Nov 01 '25 23:11

Xesenix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!