【问题标题】:mat sort works one time and then gives errormat sort 工作一次然后给出错误
【发布时间】:2020-10-02 16:23:33
【问题描述】:

我有一个带排序功能的动态垫表

dataSource: MatTableDataSource<MemberList>;
  @Output() walkthroughData: EventEmitter<number> = new EventEmitter();
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  data: any;
  memberList: MemberList[];
  membersCount: number;
ngOnInit(): void {
    setTimeout(() => {
      this.dataSource.sort = this.sort;
    });

    this.teamService.getTeamMembers().subscribe((response) => {
      this.data = response['data']['result'];

      this.memberList = this.data.map(({ name, role, email }) => ({
        teamMember: Object.values(name).join(' '),
        email,
        role: role?.name,
        assignedOn: [
          'LA Care Health Plan',
          'LA Care Health Plan',
          'LA Care Health Plan',
        ],
      }));
      this.dataSource = new MatTableDataSource(this.memberList);
    });
  }

它只工作一次然后抛出错误

core.js:6210 ERROR TypeError: Cannot set property 'sort' of undefined

我做错了什么? matHeaderCellDef 和 matCellDef 相同,还导入了 mat 排序模块,我也尝试了 ngAfterViewInit 作为数据源,但同样的错误来了

【问题讨论】:

    标签: angular typescript sorting angular-material angular-material2


    【解决方案1】:

    这似乎是一个竞争条件问题,第一次是巧合。 您的 setTimeout 在您订阅之前执行,这样,您的 dataSource 变量尚未定义。

    你应该移动这段代码:

    this.dataSource.sort = this.sort;
    

    在变量实例化后立即设置:

    this.dataSource = new MatTableDataSource(this.memberList);
    

    【讨论】:

    • 排序错误消失了,但只能在第一次使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多