3

我试图在点击分页时调用 API。最初,我静态设置了长度,它工作正常。我能够进行分页 API 调用。然后我也尝试动态设置长度并且它也可以工作,但后来它停止工作。请帮我指出我的错误。我正在 this.totalEmp 中设置内容的长度,并且也能够在 html 端打印它,但是当我尝试在 mat-paginator 中设置 [length] 时。它对我不起作用。我也尝试在 mat-paginator 中设置#paginator,但没有看到任何变化。

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;
  }
4

1 回答 1

7

错误:您在每个请求中初始化以下这些行。

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

解决方案:ngAfterViewInit通过根据您的最佳需要放置一些条件或方法,仅将这些行初始化一次。

于 2021-02-11T12:14:44.130 回答