2

In this simple stackblitz, there are only 4 initial rows and the pagination section shows only 1 page. Now, when I add rows dynamically after every 3 seconds, then also the pagination section shows a single page no matter how many rows I add. How to keep pagination in sync with table data?

Daud
  • 7,429
  • 18
  • 68
  • 115

1 Answers1

3

Since arrays are passed by reference even if we add new data that reference is not changing, Try using spread operator to add new value to array.

setInterval(() => {
    const newData = {
      albumId: 25000,
      id: 24000,
      title: 'zaalim haakim',
      url: 'google.com',
      thumbnailUrl: 'google.com',
    };
      this.products = [...this.products,newData];
    }, 3000);

OR

As mentioned by @Arnaud Denoyelle in the comment you can use Viewchild to get table instance and call reset on it to update paginator state

@ViewChild(Table) table: Table;

 setInterval(() => {
    const newData = {
      albumId: 25000,
      id: 24000,
      title: 'zaalim haakim',
      url: 'google.com',
      thumbnailUrl: 'google.com',
    };
      this.table.reset();
    }, 3000);

Forked Working Example

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • 1
    Or `this.table.reset()`. I don't know which one is less costly – Arnaud Denoyelle Mar 14 '22 at 15:37
  • https://github.com/primefaces/primeng/blob/master/src/app/components/table/table.ts#L1653 As you can see in the source file reset also internally call sort on array values. I think it's personal preference – Chellappan வ Mar 14 '22 at 15:41
  • I don't understand why adding the new row to existing data was detected and added in the table normally, but just the pagination wasn't working and we had to create a new product array – Daud Mar 15 '22 at 06:36
  • https://stackoverflow.com/questions/60036967/angular-2-change-detection-push-data-into-array – Chellappan வ Mar 15 '22 at 06:39
  • For more detailed explanation about change detection check this:https://medium.com/ngconf/simplified-angular-change-detection-e74809ff804d – Chellappan வ Mar 15 '22 at 06:40
  • That's correct, but then why does the table view get updated when we simply add certain objects to the array, without changing the array reference? Is it that the table component uses regular change detection and filter component uses OnPush? – Daud Mar 15 '22 at 11:27
  • Good question, Since Table using paginator component internally, even though table data updated paginator total length is not updated properly due to object reference – Chellappan வ Mar 15 '22 at 11:38
  • wont both methods changes page to first? any clue to stay on current page on update? – Anil P Babu Oct 18 '22 at 19:21
  • @AnilPBabu it will reset back to first page. I will check later if we can do anything about it – Chellappan வ Oct 19 '22 at 08:43