【问题标题】:problems linking paginator to MatTable将分页器链接到 MatTable 的问题
【发布时间】:2020-05-27 07:22:14
【问题描述】:

我正在尝试在 Angular 6 中为我的 mat-table 添加分页。我正在使用下面链接中的一些示例。但它不起作用:

https://material.angular.io/components/table/examples

看起来 mat-table 正确地填充了数据,并且分页器正确地显示在其下方,但它们无法连接在一起:

如您所见,分页器设置为每页5条记录,但表中当前页的记录多于记录。它还表示 0 out of 0,这进一步表明链接到表失败。

这是我的 html:

    <mat-table #table [dataSource]="dataSource" class="animate topMatDataTable”>
…
     </mat-table>
      <mat-paginator [pageSizeOptions]="[5, 10, 20]" [pageSize]="5" showFirstLastButtons></mat-paginator>

这是我的 ts 代码:

export class DynamicDataListComponent implements OnInit {
…
  dataSource : MatTableDataSource<any>;
…
  @ViewChild(MatPaginator) paginator : MatPaginator;
…
  ngOnInit() {
…
    this.loadEndpoints();
  }

  async loadEndpoints() {
…
      const endpointListObs = await this._dataStorageService.getAPIEndpointList();
      endpointListObs.subscribe((endpointList: any[]) => {
        this.dataSource = new MatTableDataSource<any>(endpointList);
        this.dataSource.paginator = this.paginator;
…
      });
…
  }
…
}

谁能告诉我我做错了什么?

谢谢。

【问题讨论】:

    标签: angular pagination angular-material mat-table


    【解决方案1】:

    我想通了。

    原来表格和分页器都在一个带有 ngIf 语句的 div 中:

    <div *ngIf="!isLoading">
    ...
    </div>
    

    这意味着在数据加载到表中之前不会呈现分页器。

    所以我所做的是,首先,将 MatTableDataSource 的初始化和分页器的分配放入 ngAfterViewInit() 中。在 loadEndpoints() 中,我将 endpointList 分配给了一个变量:

    this.endpointList = endpointList
    

    其次,如果 isLoading 为真或列表大小为 0,我在 ngAfterViewInit() 中设置超时。否则,我使用 endpointList 变量初始化 MatTableDataSource 并将其分配给分页器:

    ngAfterViewInit() {
        if (this.isLoading || this.listSize === 0) {
          setTimeout(() => {
            this.ngAfterViewInit();
          }, 1000);
        } else {
          this.dataSource = new MatTableDataSource<any>(this.endpointList);
          this.dataSource.paginator = this.paginator;
        }
    }
    

    而且它有效!

    【讨论】:

    • 你拯救了我的一天!我也给出了相同的 ngIf 条件并在不知道这个真相的情况下挣扎了几个小时! @Gibran
    【解决方案2】:

    您的模板上缺少对分页器的引用。更改您的模板以包含#paginator

    &lt;mat-paginator #paginator [pageSizeOptions]="[5, 10, 20]" [pageSize]="5" showFirstLastButtons&gt;&lt;/mat-paginator&gt;

    【讨论】:

      【解决方案3】:

      您是否将数据源分页器设置为您的分页器?

      ngOnInit() {
          this.dataSource.paginator = this.paginator; //this sets the paginator to your datasource
       ....
          this.loadEndpoints();
      }
      

      【讨论】:

        【解决方案4】:
        <div [hidden]="!isLoading">
        ...
        </div>
        

        PS:我知道这个问题已经过时并且已经提供了解决方案。我遇到了同样的问题,它对我有用。使用隐藏解决了我的问题。留在这里留给未来的访客。 credit

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-04
          • 2019-05-15
          • 2012-04-16
          • 1970-01-01
          • 2017-09-24
          • 1970-01-01
          • 1970-01-01
          • 2021-01-01
          相关资源
          最近更新 更多