'Property 'sort' has no initializer and is not definitely assigned in the constructor
I am trying to use MatSort Module to sort my Table in Angular Material but I get this error:
Property 'sort' has no initializer and is not definitely assigned in the constructor.
This is my ts file:
import { Component, OnInit, ViewChild } from '@angular/core';
import { Personal } from 'src/app/models/personal.model';
import { PersonalService } from 'src/app/services/personal.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSort, MatSortModule, MatSortHeader } from '@angular/material/sort'
@Component({
selector: 'app-personal-list',
templateUrl: './personal-list.component.html',
styleUrls: ['./personal-list.component.css']
})
export class PersonalListComponent implements OnInit {
personals?: Personal[];
currentPersonal?: Personal;
currentIndex = -1;
name = '';
PERSONAL_DATA : Personal[] = []
displayedColumns: string[] = ['name', 'action'];
dataSource = new MatTableDataSource<Personal>(this.PERSONAL_DATA);
@ViewChild(MatSort) sort: MatSort;
constructor(private personalService: PersonalService) { }
ngOnInit(): void {
this.getAllPersonalTable();
}
private getAllPersonalTable(){
let resp = this.personalService.getAllPersonal();
resp.subscribe(report =>this.dataSource.data=report as Personal[]);
this.dataSource.sort = this.sort;
}
}
The error occurs in this line
@ViewChild(MatSort) sort: MatSort;
And yes, I have tried sort!
. This removes the error, but fails to compile my page. Same goes for "strictPropertyInitialization": false,
in tsconfig.json file.
Any help on how to solve is much appreciated!!!
Solution 1:[1]
The problem I faced was exactly the same as you. It is because Angular 12 enables stricts mode in typescript (reference here).
Try with:
@ViewChild(MatSort, { static: false }) sort!: MatSort;
Solution 2:[2]
If you are using latest version of Angular, use
@ViewChild(MatSort) sort = new MatSort();
Basically it's typescript compiler error.
In the new versions, typescript has introduced strick class Initialization.
In Angular 12 or higher you may face this issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Arun |