I am paginating my table using mat-paginator. The pagination works fine when the first time the page is loaded. However if I perform an CRUD operation then the pagination does not work. All of the rows are displayed in the same page. I think its because I am using pagination inside *ngIf to show result table on condition. I researched on google and tried some solution like using [hidden], set static to false in @viewchild pagination field. I am not sure how to fix this issue.
export class UsersComponent implements OnInit, OnDestroy {
public dataSource = new MatTableDataSource<IUser>();
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(
){
}
ngOnInit(): void {
this.dataSource = new MatTableDataSource<IUser>(this.users);
}
ngAfterViewInit(): void {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
}
}
users.component.html
<div class="users-container" *ngIf="UsersResults">
<mat-card fxLayout="column" @fade class="users-card mat-elevation-z6">
<div fxFlex="10" fxlayout="row" fxLayoutAlign="center center">
<h1 class="heading">Users</h1>
<button mat-raised-button class="user-button" (click)="showCreateUserView()">Create User</button>
</div>
<div fxFlex="80">
<span fxFlex="3"></span>
<div fxFlex="100">
<table class="result-table" mat-table [dataSource]="dataSource" matSort matSortStart="desc">
<ng-container matColumnDef="username">
<th mat-header-cell *matHeaderCellDef mat-sort-header id="username">Username</th>
<td mat-cell *matCellDef="let element">
<button mat-button(click)="showEditUserView(element)" [disableRipple]="true" matToolTip="click to edit user">{{element.username}}</button>
</td>
</ng-container>
<ng-container matColumnDef="admin">
<th mat-header-cell *matHeaderCellDef id="status">Status</th>
<td mat-cell *matCellDef="let element">
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator
[pageIndex]="0"
[pageSize]="7"
[pageSizeOptions]="[15, 30]">
</mat-paginator>
</div>
</div>
</mat-card>
</div>
I found the solution. Looks like this issue is caused by Angular where view child does not catch elements with *ngIf in ngAfterViewInit so this workaround solution worked for me. Github link for the similar issue provided below:
If there is better solution for this, please feel free to post it here.
Remove the code:
from ngAfterViewInit and add the following code:
http://www.github.com/angular/components/issues/10205