【问题标题】:Mat-sort is not working in angular mat-table垫排序在角垫表中不起作用
【发布时间】:2019-07-19 21:31:55
【问题描述】:

我的 mat-table 工作正常,但是在按照官方 api 文档添加 mat-sort 时,它在 ngAfterViewInit 失败并显示以下消息

无法设置未定义的属性“排序” aq LeadsComponent.push../src/app/leads/leads.component.ts.LeadsComponent.ngAfterViewInit

已经有一个关于 Mat-table Sorting Demo 的 SO 帖子并尝试了它们,但我仍然无法让它工作。

有人能帮我解决这个问题吗?官方示例使用组件本身中定义的“静态”MatTableDataSource,但是我从后端查询。

MatSortModule 已经导入 app.module.ts,mat-sort-header 指令应用于列,ngAfterViewInit 已经与官方示例中的完全一样...

 export class LeadsComponent implements OnInit,AfterViewInit  {

  displayedColumns: string[] = ['name', 'leadStatus', 'mobile', 'email', 'actions'];
  dataSource: MatTableDataSource<LeadsChildObject>;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(public dialog: MatDialog, private dashBoardService: LeadsService,
    private toast: ToastrService) {
  }

    ngAfterViewInit() {
        this.dataSource.sort = this.sort;
      }

      ngOnInit() {
        this.dashboardService.getFeedback.subscribe(
          res => {
            this.leadlist= res;
            this.dataSource = new MatTableDataSource(this.leadlist);
          }
        );
      }
    }
}

【问题讨论】:

  • 你在哪里初始化this.dataSource?
  • 我更新了我的代码,请立即查看

标签: angular angular-material angular-material-table


【解决方案1】:

无法设置未定义的 aq LeadsComponent.push../src/app/leads/leads.component.ts.LeadsComponent.ngAfterViewInit 的属性“排序”

此错误是指在未定义属性上调用“排序”,在您更新后,该属性是数据源属性,因为您没有对其进行初始化。

它没有被初始化,因为你的subscribe()(你初始化它的地方)是异步,因此,初始化发生在之后 ngAfterViewInit()发生。

请在您的ngOnInit() 中初始化它:

ngOnInit() {
  // This line of code below:
  this.dataSource = new MatTableDataSource<LeadsChildObject>();

  this.dashboardService.getFeedback.subscribe(
    res => {
      this.leadlist= res;
      this.dataSource = new MatTableDataSource(this.leadlist);
      this.dataSource.sort = this.sort;
    }
  );
}

您的方法存在的问题是,您误将MatTableDataSource 与普通数组方法(简单表方法)一起使用。请找到这个documentation 来实现MatTableDataSource 方法

【讨论】:

    【解决方案2】:

    你可以试试这个方法吗:

      ngOnInit() {
        this.dashboardService.getFeedback.subscribe(
          res => {
            this.leadlist= res;
            this.dataSource = new MatTableDataSource(this.leadlist);
            this.dataSource.sort = this.sort;  //new line, also remove same from viewinit
          }
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多