juhi
juhi

Reputation: 578

mat sort works one time and then gives error

I have a dynamic mat table with sort

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);
    });
  }

It works only single time and then throws error

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

What I am doing wrong? matHeaderCellDef and matCellDef are same, mat sort module is also imported and i have also tried ngAfterViewInit for the datasource but same error comes

Upvotes: 0

Views: 472

Answers (1)

Elias Dal Ben
Elias Dal Ben

Reputation: 439

This seems to be a race-condition issue, the first time is working by a coincidence. Your setTimeout is executing before your subscribe, this way, your dataSource variable isn't defined yet.

You should move this code:

this.dataSource.sort = this.sort;

To set right after your variable is instantiated:

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

Upvotes: 1

Related Questions