Search code examples
angularprimengprimeng-turbotable

How to scroll to last row on a PrimeNG TurboTable component


I'm using a PrimeNG TurboTable component on an Angular 7 application and there's a button to add new rows to it. The problem is that, when a new row is added, the user has to scroll down to the bottom of the table to start editing it. How could I scroll to it?

This is how I define the table in the template:

<p-table [value]="gridOptions" [scrollable]="true" scrollHeight="13em" 
selectionMode="single" [(selection)]="selectedOption" 
(onEditComplete)="onDataChanged($event)"
(onRowReorder)="onDataChanged($event)">
  [ ... ]

</p-table>

And this is the 'Add option' handler:

onAddOption() {
  // This adds a new option to the TurboTable
  this.gridOptions.push({ name: "", arg: "", comment: "", scope: this.scope });

  // I expected that selecting an option would scroll to it, but it doesn't work
  this.selectedOption = this.gridOptions[this.gridOptions.length-1];
}

Any ideas? Thanks!


Solution

  • UPDATE: add demo

    You only need to use javascript

    $('.ui-table-scrollable-body').scrollTop($('.ui-table-scrollable-body')[0].scrollHeight);
    

    or animated:

    $(".ui-table-scrollable-body").animate({ scrollTop: $('.ui-table-scrollable-body').prop("scrollHeight")}, 200
    

    Without jquery:

    TS:

    scroll(table: Table) {
        let body = table.containerViewChild.nativeElement.getElementsByClassName("ui-table-scrollable-body")[0];
        body.scrollTop = body.scrollHeight;
      }
    

    HTML:

    <p-table #table [columns]="cols" [value]="sales" [scrollable]="true" scrollHeight="200px"> ... </p-table>
    <button (click)="scroll(table)">Scroll</button>