Material pagination does not work when inside *ngIf

Viewed 1104

I have this code with pagination inside, but the pagination does not work. It always shows all elements. But removing *ngIf from container div, it just woks. Why it is so? How to make it work with *ngIf? I really need to use it.

<div *ngIf="savingTransactionsDataSource" class="mat-elevation-z8">

    <table mat-table [dataSource]="savingTransactionsDataSource">
        <ng-container [matColumnDef]="column" *ngFor="let column of items">
          ...
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="savingColumnsToDisplay; sticky: true;"></tr>
        <tr mat-row *matRowDef="let row; columns: savingColumnsToDisplay;"></tr>
    </table>

    <mat-toolbar class="mat-toolbar-sticky">
        <mat-toolbar-row>

            <span class="spacer"></span>

            <mat-paginator [length]="savingTransactionsDataSource.data.length"
                           [pageSize]="5"
                           [pageSizeOptions]="[5, 10, 15, 20]"
                           showFirstLastButtons>
            </mat-paginator>

        </mat-toolbar-row>
    </mat-toolbar>
</div>
1 Answers

According to this GitHub issue, the paginator breaks inside an ngIf, but you can try to use this snippet to get around the problem:

@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.setDataSourceAttributes();
  }

  setDataSourceAttributes() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

Alternatively, another solution posted was to use the hidden attribute instead of ngIf.

<div [hidden]="isLoading">
  <mat-table [dataSource]="dataSource">
  ...
  </mat-table>
</div>
Related