Reputation: 3
I am trying to use mat-paginator where the data is dynamically loaded from a service on submit button click. For some reason all data is loaded into the first page and pagination doesn't seem to be working. I also have another button (refresh) that would fetch the data from back end service and load the table again. When this button is clicked, pagination seems to work fine. I have tried all solutions provided in other questions in stackoverflow, but none of them seems to solve the problem. Please see relevant code snippet below and let me know your suggestions,
HTML
<nb-tab tabTitle="Transactions">
<div class="mat-elevation-z8">
<mat-paginator [length]="this.dataLength" [pageSize]="5" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons>
</mat-paginator>
<table *ngIf="rewardsFound" mat-table [dataSource]="dataSource">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="transactionDt">
<th mat-header-cell *matHeaderCellDef> Transaction Dt. </th>
<td mat-cell *matCellDef="let element"> {{element.transactionDt}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="transactionType">
<th mat-header-cell *matHeaderCellDef> Transaction Type </th>
<td mat-cell *matCellDef="let element"> {{element.transactionType}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div *ngIf="!rewardsFound">
<label class="label col-form-label-field">No transaction history found for this member</label>
</div>
</nb-tab>
COMPONENT TS
dataSource = new MatTableDataSource()
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
this.loading = true
this.getService.getTransHistory(this.InputData)
.subscribe (
(data:Histarray)=>{
if (data.responseStatus == "001") {
this.dataSource = new MatTableDataSource(data.HistOut)
setTimeout(() => this.dataSource.paginator = this.paginator)
this.dataLength = data.rewardHistCount
} else if (data.responseStatus == "004") {
this.dataSource = new MatTableDataSource()
this.dataLength = 0
}
},
(err:any)=>{
this.loading = false
this.memberFound = true
this.searchDone = true
}
)
}
Upvotes: 0
Views: 2278
Reputation: 391
It looks like the paginator is still undefined when assigned to your datasource during the initial load and due to which the table doesn't paginates.
The below approach will assign the paginator when the paginator element is initialized and should solve your issue,
_paginator: MatPaginator;
@ViewChild(MatPaginator, {static: false}) set matPaginator(paginator: MatPaginator) {
this._paginator = paginator;
if (this.dataSource) {
this.dataSource.paginator = paginator;
}
}
During reload of data use this._paginator
Upvotes: 2