Angular MatPaginator not working

2019-02-16 14:15发布

问题:

I have 2 components. Both have mat-table and paginators and pagination is working for one component and not working for the other component though the code is similar. Below is my html:

<div class="mat-elevation-z8">

    <mat-table [dataSource]="dataSource" matSort>

      <ng-container matColumnDef="col1">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Column1 </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.col1}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="col2">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Column2 </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.col2}} </mat-cell>
      </ng-container>

      <!-- Different columns goes here -->

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;">
      </mat-row>
    </mat-table>

    <mat-paginator #scheduledOrdersPaginator [pageSizeOptions]="[5, 10, 20]"></mat-paginator>
  </div>

And below is my code in component.ts:

dataSource: MatTableDataSource<any>;
displayedColumns = ['col1', 'col2', ... ];
@ViewChild('scheduledOrdersPaginator') paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit(): void {
    // Load data
    this.dataSource = new MatTableDataSource(somearray);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
}

Similar code is working for the other component and table is getting rendered with the pagination properly, no clue what's wrong with this code.

Any help would be really appreciated

回答1:

I resolved a similar issue by surrounding the instantiation with a timeout. Try this :

setTimeout(() => this.dataSource.paginator = this.paginator);


回答2:

In my case, the <mat-paginator> element was inside a container that had an *ngIf on it, which did not render until the data loaded asynchronously. This causes this.paginator to be undefined even in ngAfterViewInit. This causes it to silently fail as MatTableDataSource has no problem with you setting paginator to undefined.

The solution was to move the <mat-paginator> outside of the *ngIf'd container

Hopefully, this helps someone who is in the same situation as me.



回答3:

Although selected answer works and solves the problem it is still a workaround. This is proper and more elegant way to deal with the problem.

Try adding AfterViewInit interface to your class, then put this.dataSource.paginator = this.paginator inside ngAfterViewInit() method

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

then you would not have to call workaround setTimeout.



回答4:

To make it work I had to set the paginator after the data was fetched from source

getVariables() {
    this.activeRoute.params.subscribe(params => {
        if (params['id'] && (params['type'] === Type.CodeList)) {
            this.dataService
                .getItems(this.currentLanguage, params['id'])
                .subscribe((items: any) => {
                    this.dataSource.data = this.items;
                    this.dataSource.paginator = this.paginator;
                })
        }
    })
}


回答5:

  <mat-paginator
        #scheduledOrdersPaginator
          (page)="pageEvent($event)">
        </mat-paginator>
         pageEvent(event){
         //it will run everytime you change paginator
           this.dataSource.paginator = this.paginator;
          }


回答6:

I am quite a beginner in angular and typescript, but after having the same problem (except, that for me sorting didn't work either), what helped was creating a function 'refreshDataScource()' and having it called from ngAfterViewInit() as well as after each time the server responds with new data. In this function I simply refresh the dataSource with the paginator and the sort. Like this:

refreshDataSource() {
    this.dataSource = new MatTableDataSource(myDataArray);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

It fixed the paginator and the sort. Everything works now perfectly. However I am not sure if it is just a workaround or a real fix.



回答7:

Using setTimeOut() will solve the issue temporarily, however, this will again fail to work if you are pushing a huge load of Data [say 1000 rows] into MatDataSource.

we've found that the MatTable loads very slowly if a large data set is set before you set the data-source paginator.

ngOninit(){
// initialize dataSource here
}
    ngAfterViewInit() {
  this.dataSource.sort = this.sort;
  this.dataSource.paginator = this.paginator;

  /* now it's okay to set large data source... */
  this.dataSource.data = [GetLargeDataSet];}

So, initialize the data-Source at first place and set the properties like "Paginator" or "Sort" before pushing the data into the source into the "Data" property.