我有一个动态矩阵表,有排序
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的数据源,但同样的错误出现了。
这似乎是一个竞赛条件的问题,第一次是通过巧合工作的,你的setTimeout是在你的subscribe之前执行的,这样一来,你的dataSource变量还没有定义。
你应该移动这段代码。
this.dataSource.sort = this.sort;
在变量被实例化之后再进行设置。
this.dataSource = new MatTableDataSource(this.memberList);