首页 > 解决方案 > ERROR 错误:无法设置未定义的属性“分页器”

问题描述

我正在使用以下示例创建 Angular 材质表: https ://github.com/marinantonio/angular-mat-table-crud 。该示例使用来自“@angular/cdk/table”的 { DataSource } 连接到表。

对于我的项目,我需要使用来自“@angular/material”的 MatTableDataSource 作为表数据连接器,一旦我将代码更改为使用 MatTableDataSource,我就会不断收到 TypeError: Cannot set property 'paginator' of undefined

我的问题有一个重现 https://stackblitz.com/edit/angular-3rhawr

我究竟做错了什么 ?任何帮助将不胜感激。

标签: angularangular-material

解决方案


this.exampleDatabase.getAllIssues()本质上是异步的,可能需要一些时间才能完成。但ngAfterViewInit会在此之前被调用。并且由于dataSource设置在 的subscribe块中this.exampleDatabase.getAllIssues(),因此错误。

通过从块ngAfterViewInit中移动代码来修复它。subscribe像这样的东西:

public loadData() {
  this.exampleDatabase = new DataService(this.httpClient);
  this.exampleDatabase.getAllIssues().subscribe(data => {
    this.dataSource = new MatTableDataSource(data);
    this.dataSource.data = data;
    this.dataLength = data.length;

    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  });
}

这是一个工作示例 StackBlitz,您的参考没有错误。


推荐阅读