垫排序在角度垫表中不起作用

Abh*_*Ram 2 angular-material angular angular-material-table

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

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

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

有人可以帮我解决这个问题吗?官方示例使用组件本身定义的“静态”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);
          }
        );
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*bos 5

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

此错误是指对未定义的属性调用“sort”,该属性在更新后是数据源属性,因为您没有初始化它。

它没有初始化,因为你的subscribe()(初始化它的地方)是async,因此,初始化发生在发生之后 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;
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

您的方法中的问题在于,您错误地使用了MatTableDataSource普通数组方法(简单表方法)。请找到此文档来实施该MatTableDataSource方法