Search code examples
angularangular-materialmat-pagination

Mat-pagination does not direct me to new page afte adding row


I am trying to implement an inline row-adding to my table with pagination. To ensure the new row is visible, I'm directing the user to the last page with

this.dataSource.paginator.lastPage();

However, when there is just enough data to fill page(s) up to the limit of page size, e.g. 10,20,30 on page size 10, It will not direct me to the new page (with only the one row I just added). (At the same time, paginator show correct number of rows at the bottom and I can navigate to it manually)

Sure enough, I can see that this.dataSource.paginator.length shows outdated number (even though I have already done the

const data = this.dataSource.data;
data.push(log);
this.dataSource.data = data;

trick to push new row to the datasource)

I have tried some hacks that I've encountered across the Stackoverflow, like

    this.dataSource.paginator._changePageSize(this.dataSource.paginator.pageSize);

Or try to force navigate to next page with

this.dataSource.paginator.nextPage();

My component

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  ngOnInit() {
    this.dataSource = new MatTableDataSource();
  }
  request(params?) {
    this.logApi.getList(params)
      .toPromise()
      .then(data => {
        this.dataSource.data = data;
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
  }

  addLog() {
const log = new Log();
log.assignee = '';
log.timeSpentTotal = 0;
this.checkRowValid();
const data = this.dataSource.data;
data.push(log);
this.dataSource.data = data;
this.dataSource.paginator.lastPage();
if (this.dataSource.paginator.hasNextPage()) {
 this.dataSource.paginator.nextPage();
}

}

HTML

<nb-card>
  <nb-card-header>
    Logs <button nbButton hero status="success" (click)="addLog()" size="tiny" [disabled]="rowAddMode || rowEditMode">Add new</button>
  </nb-card-header>
  <table [dataSource]="dataSource" matSort mat-table [ngClass]="'mat-elevation-z8'" multiTemplateDataRows>
    /* ... */
  </table>
  <mat-paginator [pageSizeOptions]="[10]" showFirstLastButtons></mat-paginator>

Needless to say, I have stripped some code for length

Any ideas?


Solution

  • Manually updating the paginator length seems to work.

      addLog() {
        const log = new Log();
        log.assignee = "";
        log.timeSpentTotal = 0;
        this.checkRowValid();
        const data = this.dataSource.data;
        data.push(log);
        this.dataSource.data = data; 
        this.paginator.length = data.length; // 👈 Add this
        this.dataSource.paginator = this.paginator; // 👈 Add this
        this.dataSource.paginator.lastPage();
      }
    

    Stackblitz here, I had to use different data, of course.