Angular MatPaginator not working

前端 未结 30 1582
情歌与酒
情歌与酒 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条回答
  •  Happy的楠姐
    2020-12-05 00:01

    This is because of this.paginator is undefined at the time it going to assign to this.dataSource.paginator.

    if you using static data this will work

     @ViewChild(MatPaginator, {static: false}) paginator: MatPaginator; // For pagination
     @ViewChild(MatSort, {static: false}) sort: MatSort; // For Sort
    
     ngOnInit(): void {
       this.dataSource.data = this.dataList; // Data list is data array 
     }
    
     ngAfterViewInit(): void {
       this.dataSource.paginator = this.paginator; // For pagination
       this.dataSource.sort = this.sort; // For sort
     }
    

    if you using dynamic data (Data from API) this will work

    For Pagination

      @ViewChild(MatPaginator, {static: false})
      set paginator(value: MatPaginator) {
        if (this.dataSource){
          this.dataSource.paginator = value;
        }
      }
    

    For Sort

      @ViewChild(MatSort, {static: false})
      set sort(value: MatSort) {
        if (this.dataSource){
          this.dataSource.sort = value;
        }
      }
    

    As a side note im using Angular 9 at the movement.

提交回复
热议问题