Everything was running smoothly with my mat-table until I tried adding mat-sort as per the official API documentation. Unfortunately, it failed at ngAfterViewInit with the following error message:
ERROR TypeError: Cannot set property 'sort' of undefined
Check out this screenshot for the first error .. Not sorting
Despite the data being correctly displayed from the API, I attempted to move the code to the component's constructor to only set this in the onInit:
this.listData.sort = this.sort;
I made sure to import the module in the app.module.
Here are the contents of my three files:
Componenet.html
<mat-table [dataSource]="listData" matSort>
<ng-container matColumnDef="gender">
<mat-header-cell *matHeaderCellDef mat-sort-header>Gender</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.gender}}</mat-cell>
</ng-container>
<ng-container matColumnDef="firstname">
<mat-header-cell *matHeaderCellDef mat-sort-header>First Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.firstname}}</mat-cell>
</ng-container>
component.ts
import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {PersonneService} from '../../shared/personne.service';
import { MatTableDataSource, MatSort} from '@angular/material';
import {Personne} from '../../personne';
@Component({
selector: 'app-personne-list',
templateUrl: './personne-list.component.html',
styleUrls: ['./personne-list.component.css']
})
export class PersonneListComponent implements AfterViewInit {
personne: any = [];
constructor(private service: PersonneService) {
this.service.getPersonnes().subscribe((data: {}) => {
this.personne = data;
this.listData = new MatTableDataSource(this.personne);
});
}
listData: MatTableDataSource<Personne>;
displayedColumns: string[] = ['gender', 'firstname', 'lastname', 'address', 'city', 'state', 'ordertotal', 'actions'];
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
console.log({SORT: this.sort});
this.listData.sort = this.sort;
}
}
Service.ts :
import { Injectable } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {Personne} from '../personne';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PersonneService {
constructor(private http: HttpClient) {}
// More service methods here
getPersonnes() {
return this.http.get('http://localhost:3000/api/personnes');
}
While researching this issue, I stumbled upon this answer on Stack Overflow:
To address the issue, I added the following line to the html:
[hidden]="!listData.data" matSort
Now, when I click to sort, it does so but not accurately, and I encounter another error in the console:
ERROR TypeError: Cannot read property 'data' of undefinedHere's a screenshot for the second error
Your assistance in resolving this would be greatly appreciated.