2
votes

I'm trying to make the angular material 2 paginator component work with the table component (mat-table directive).

I followed the mat-table documentation to add a paginator, trying to make their example work with my existing working mat table.

In the component.html I have a working mat table, and a paginator:

<div class="example-container">
    <mat-table [dataSource]="dataSource">
    // columns and rows
    </mat-table>
    <mat-paginator #paginator
                   [pageSize]="10"
                   [pageSizeOptions]="[5, 10, 20]"
                   [showFirstLastButtons]="true">
    </mat-paginator>
</div>

The component that uses this html implements ngOnInit:

ngOnInit() {
    myapi.apirequest()
          .subscribe((dataResponse: any) => {
            this.dataSource = new BasicDataSource(dataResponse);
            this.dataSource.paginator = this.paginator;
            console.log(this.paginator);
          });
      });
  }

And the component gets the paginator using @ViewChild:

@ViewChild(MatPaginator) paginator: MatPaginator;

The issue is the paginator does nothing and the next and previous buttons are greyed out.

The console.log(this.paginator) gives :

_changeDetectorRef: Object { _view: {…}, _viewContainerRef: null, _appRef: null } ​ _displayedPageSizeOptions: Array(3) [ 5, 10, 20 ] ​ _hidePageSize: false ​ _initialized: true ​ _intl: Object { itemsPerPageLabel: "Items per page:", nextPageLabel: "Next page", previousPageLabel: "Previous page", … } ​ _intlChanges: Object { closed: false, syncErrorThrown: false, syncErrorThrowable: false, … } ​ _length: 0 ​ _pageIndex: 0 ​ _pageSize: 10 ​ _pageSizeOptions: Array(3) [ 5, 10, 20 ] ​ _showFirstLastButtons: true ​ page: Object { _isScalar: false, closed: false, isStopped: false, … } ​ proto: Object { pageIndex: Getter & Setter, length: Getter & Setter, pageSize: Getter & Setter, … }

I don't know how to debug / understand what causes the paginator not to work.

My BasicDataSource extends DataSource and using ngAfterViewInit doest work because this.datasource is undefined at this point (api call not done).

1

1 Answers

5
votes

Initialize paginator after view init.

 ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

Initialize datasource with blank array.

ngOnInit() {
            this.dataSource = new BasicDataSource([]);
    myapi.apirequest()
          .subscribe((dataResponse: any) => {
            this.dataSource = new BasicDataSource(dataResponse);
            this.dataSource.paginator = this.paginator;
            console.log(this.paginator);
          });
      });
  }