4

I am trying to call API on the click of pagination. Initially, I had set the length statically and it was working fine. I was able to do a pagination API call.And then I had tried to set the length dynamically as well and it worked too, but later on, it stopped working. Please help me to point out my mistake. I am setting the length of content in this.totalEmp and able to print it on html side as well but when I am trying to set in mat-paginator for [length]. It is not working for me.I tried to set #paginator in mat-paginator as well but no change was seen.

Below is my implementation



**HTML:**
<mat-paginator 
    [length]="totalEmp"
    [hidden]="normalPagination"
    [pageSize]="2" 
    [pageSizeOptions]="[2]"
    [pageIndex]="pageIndex"
    (page)="pageEvent = getDataByPagination($event)"></mat-paginator>

**.ts file Code**

export class EmpComponent implements OnInit {
 
         dataSource: any;
         totalEmp: number=0;
         normalPagination: boolean;
        
        @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
         @ViewChild(MatSort, { static: true }) sort: MatSort;
        
        ngOnInit() {
            this.getTableContentCount();
          }
        
        
         getTableContentCount() {
            this.myService.CountService().subscribe(
              (response: any) => {
                if (response) {
           
                  this.totalEmp = response;
                  this.getServerData(0,this.totalEmp);
                }
              },
              (error: any) => { }
            );
          }
        
        public getDataByPagination(event?: PageEvent) {
    this.myService.getPaginationService(event).subscribe(
      response => {
        if (response) {
          this.showLoader=true;
          this.normalPagination=false;
          this.total = this.totalEmp;      
          this.allData=response;
          this.dataSource = new MatTableDataSource(this.allData);
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
          this.showLoader=false;
        }
      },
      error => {
        // handle error
      }
    );
    return event;
  }
Shashwat Tyagi
  • 255
  • 5
  • 15

2 Answers2

8

Error: You're initializing these below lines in every request.

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

Solution: Initialize these lines only once either by placing some condition or in ngAfterViewInit method as per your best need.

WasiF
  • 26,101
  • 16
  • 120
  • 128
1

use @ViewChild(MatPaginator, { read: true }) paginator: MatPaginator; to make paginator work

https://www.freakyjolly.com/angular-material-12-server-side-table-pagination-example/#comment-23556

rofrol
  • 14,438
  • 7
  • 79
  • 77