htmlangularangular-materialpaginatormat-pagination

I have a problem with the Angular paginator - it doesn't work


I have a problem with Angular Material's paginator.

It is instantiated in my class:

@ViewChild("paginator") paginator: MatPaginator;

After getting the data from my API called by ngOnInit(), I set the pager to the data:

this._service.get().subscribe({
      next: (response) => {
        this._dataSource.data = response.Content || [];
        if (this.paginator) {
          this.paginator.pageSize = this.pageSize;
          this.paginator._changePageSize(this.pageSize);
          this._dataSource.paginator = this.paginator;
        }
      },
      error: (error) => {
        this._dialogService.openError(error);
      }
    });

Then I try to force paginator again, but it doesn't work:

ngAfterViewInit() {
    if (this.paginator) {
      this.paginator.pageSize = this.pageSize;
      this.paginator._changePageSize(this.pageSize);
    }
    this._dataSource.paginator = this.paginator;
  }

In my HTML, I have this table:

<table mat-table [dataSource]="_dataSource" multiTemplateDataRows>
      <ng-container matColumnDef="...">
        <th mat-header-cell *matHeaderCellDef> ... </th>
        <td mat-cell *matCellDef="let element"> {{element....}} </td>
      </ng-container>
      <ng-container matColumnDef="...">
        <th mat-header-cell *matHeaderCellDef> ... </th>
        <td mat-cell *matCellDef="let element"> {{element....}} </td>
      </ng-container>
    .......
        <!-- Header & Row Definitions -->
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  
        <tr class="mat-row" *matNoDataRow>
            <td class="mat-cell" [attr.colspan]="displayedColumns.length">
                Data not found
            </td>
        </tr>
    </table>
    <mat-paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 50]" showFirstLastButtons>
    </mat-paginator>
</table> 

Solution

  • You forgot to add the template reference variable in the HTML for the @ViewChild.

    <mat-paginator #paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 50]" showFirstLastButtons></mat-paginator>
    

    We can also directly reference the component like below.

    @ViewChild(MatPaginator) paginator: MatPaginator;
    

    After doing this the page size is set.

    Full Code:

    HTML:

    <table mat-table [dataSource]="_dataSource" class="mat-elevation-z8">
      <!--- 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="position">
        <th mat-header-cell *matHeaderCellDef>No.</th>
        <td mat-cell *matCellDef="let element">{{element.position}}</td>
      </ng-container>
    
      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef>Name</th>
        <td mat-cell *matCellDef="let element">{{element.name}}</td>
      </ng-container>
    
      <!-- Weight Column -->
      <ng-container matColumnDef="weight">
        <th mat-header-cell *matHeaderCellDef>Weight</th>
        <td mat-cell *matCellDef="let element">{{element.weight}}</td>
      </ng-container>
    
      <!-- Symbol Column -->
      <ng-container matColumnDef="symbol">
        <th mat-header-cell *matHeaderCellDef>Symbol</th>
        <td mat-cell *matCellDef="let element">{{element.symbol}}</td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
    <mat-paginator
      #paginator
      [pageSize]="5"
      [pageSizeOptions]="[5, 10, 25, 50]"
      showFirstLastButtons
    ></mat-paginator>
    

    TS:

    import { Component, ViewChild } from '@angular/core';
    import { MatTableDataSource, MatTableModule } from '@angular/material/table';
    import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
    import { of, delay } from 'rxjs';
    
    export interface PeriodicElement {
      name: string;
      position: number;
      weight: number;
      symbol: string;
    }
    
    const ELEMENT_DATA: PeriodicElement[] = [
      { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
      { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
      { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
      { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
      { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
      { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
      { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
      { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
      { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
      { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
    ];
    
    /**
     * @title Basic use of `<table mat-table>`
     */
    @Component({
      selector: 'table-basic-example',
      styleUrl: 'table-basic-example.css',
      templateUrl: 'table-basic-example.html',
      imports: [MatTableModule, MatPaginatorModule],
    })
    export class TableBasicExample {
      displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
      _dataSource = new MatTableDataSource();
      pageSize = 10;
        @ViewChild('paginator') paginator: MatPaginator;
    
      ngOnInit() {
        of(ELEMENT_DATA)
          .pipe(delay(2000))
          .subscribe({
            next: (response) => {
              this._dataSource.data = response || [];
              if (this.paginator) {
                this.paginator.pageSize = this.pageSize;
                this.paginator._changePageSize(this.pageSize);
                this._dataSource.paginator = this.paginator;
              }
            },
            error: (error) => {
              console.error(error);
            },
          });
      }
    }
    

    Stackblitz Demo