Angular MatPaginator not working

前端 未结 30 1619
情歌与酒
情歌与酒 2020-12-04 23:05

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

30条回答
  •  无人及你
    2020-12-04 23:52

    Angular 7+ (8/9) There is another elegant solution to solve that problem.

    Short Version

    Immediately after setting data source invoke ChangeDetectorRef.detectChanges().

    Long Version

    Step1:

    Import ChangeDetectorRef & Material related stuff

    import { ..., ChangeDetectorRef } from '@angular/core';
    import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
    

    Step2:

    Set class-properties in your component

    @ViewChild(MatSort) sort: MatSort;
    @ViewChild(MatPaginator) paginator: MatPaginator;
    

    Step3:

    Inject ChangeDetectorRef in your constructor

    constructor (..., private cdr: ChangeDetectorRef, ...) { ... }
    

    Step4:

    Set data source and invoke detectChanges()

    this.dataSource = new MatTableDataSource (MY_DATA);
    this.cdr.detectChanges();
    

    Optional Steps:

    After that, you can set other properties like

    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    

提交回复
热议问题