4

I need to have the selected page of my p-table to be the last page.

I am able to get my table object:

@ViewChild('myTable') myTable: DataTable;

ngOnInit() {

    this.subService.subsUpdated.subscribe(result => {
      this.fetchSubcontracts();
    });

    this.appForm.subAdded.subscribe(result => {
      this.added = 4;
      this.fetchSubs();
    });

  }

I tried binding the [first] and [paginatorPosition] properties on my p-table to a property but that didn't work.

<p-table #myTable
           [value]="subs"
           sortMode="multiple"
           selectionMode="single"
           (onRowSelect)="onRowSelect($event)"
           (onRowUnselect)="onRowUnselect($event)"
           [(selection)]="selectedSub"
           [columns]="columns"
           dataKey="id"
           [paginator]="subs.length > 0"
           [rows]="5"
           [first]="added"
           >
Antikhippe
  • 6,316
  • 2
  • 28
  • 43
Drew13
  • 1,301
  • 5
  • 28
  • 50

4 Answers4

3

This worked for me :

@ViewChild('dt', { static: false }) table: Table;

this.table.first = Math.floor(this.table.totalRecords / this.table.rows) * this.table.rows;
this.table.firstChange.emit(this.table.first);
this.table.onLazyLoad.emit(this.table.createLazyLoadMetadata());
Pascal Bayer
  • 2,615
  • 8
  • 33
  • 51
r_piramoon
  • 141
  • 1
  • 6
2

first property is the index of the first row to be displayed not the index of the first page to be displayed.

In your table properties, you have set 5 rows per page so if added equals 4, you will always stay on the first page which contains the 4th row.

So added should be something like Math.floor(this.subs.length/5)

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
1

try to use onPageChange() function:

this.appForm.subAdded.subscribe(result => {
  // number of pages in the table
  const pageCount = Math.ceil(this.myTable.totalRecords / this.myTable.rows);
  // last page
  const page = pageCount - 1;
  this.myTable.onPageChange({
    pageCount,
    page,
    first: page * this.myTable.rows,
    rows: this.myTable.rows
  });
  this.fetchSubs();
});

instead of

this.myTable.totalRecords

you could also use

this.subs.length

you can also remove [first]="added" from your HTML

Andriy
  • 14,781
  • 4
  • 46
  • 50
0

Setting the "first" on p-table is notorious. It doesn't work all the time. What I've found is that, when you do it the ugly way, it works! Like so:

@ViewChild('table', { static: true }) table!: Table;

 goToPage(page: number): void {
   setTimeout(() => {
     this.table.first = (page - 1) * this.pageSize;
     this.table.firstChange.emit(this.table.first);
   }, 0);
 }
Ε Г И І И О
  • 11,199
  • 1
  • 48
  • 63