Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatPaginator gets undefined

I have replicated thsi case: Angular 5 Material Table not getting data from service

But when I try access any property from paginator I get undefined error from this objet.

Any ideas?

Thanks

like image 611
Kram_ Avatar asked Dec 01 '17 12:12

Kram_


People also ask

Why paginator is undefined in angular?

Some issues that may cause mat-paginator is undefined: You forgot to import in app. module. ts import { MatPaginatorModule } from '@angular/material'; and then declare the import in the imports array inside ngModule.


2 Answers

I got the same issue. Placing mat-paginator tag outside *ngIf resolved my issue. Make sure it is available to component class without any conditions.

like image 192
Pranav Pavan Avatar answered Sep 17 '22 13:09

Pranav Pavan


Some issues that may cause mat-paginator is undefined:

  1. You forgot to import in app.module.ts import { MatPaginatorModule } from '@angular/material'; and then declare the import in the imports array inside ngModule.

    @NgModule({ declarations: [ somestuff], imports: [ MatPaginatorModule]});

  2. Import MatPaginator inside the component you are using: import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';

  3. set the MatDataSource to be none. (only need to do this if you are going to be getting async data e.g. from a server)

    this.dataSource = new MatTableDataSource([]);

  4. Make sure you set the length property of the mat-paginator to the length of the data rows returned.

  5. Set the paginator inside NgAfterViewInit method or if that doesn't work try:

private paginator: MatPaginator; private sort: MatSort;

@ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.setDataSourceAttributes();
}

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

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

    if (this.paginator && this.sort) {
        this.applyFilter('');
    }
}
like image 31
Josh Dando Avatar answered Sep 20 '22 13:09

Josh Dando