问题

一般来说,按angular material的官方文档, 在afterViewInit里面 可以把paginator或者sort和dataSource绑定在一起。但是如果这个table是在ngIf里面,也就是要在条件满足的情况下。这个时候的

@ViewChild(MatPaginator) paginator: MatPaginator;

可能就不好用了。因为还没有渲染,对应的还是null, 当然在最新的版本里面,ViewChild提供 static: false。

方案

可以在代码里面

  sort: MatSort;
  paginator: MatPaginator;

  @ViewChild('paginator1') set matPaginator1(mp: MatPaginator) {
    this.paginator = mp;
    this.setDataSourceAttributes1();
  }

  @ViewChild('sort1') set matSort1(ms: MatSort) {
    this.sort = ms;
    this.setDataSourceAttributes1();
  }

  setDataSourceAttributes1() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }