In my Angular application, my @ViewChild instance is failing to fill HTL matSort.
mycomponent.ts:
import { MatSort } from '@angular/material';
export class MyClassComponent {
@ViewChild(MatSort) sort: MatSort;
}
ngOnInit() {
console.log(this.sort); // undefined
}
mycomponent.html:
<mat-table #table [dataSource]="dataSource" matSort>
.......................................................
.......................................................
</mat-table>
I need to use sortChange from matSort but it is always returned undefined.
It will be initialized and available in the AfterViewInit
lifecycle hook:
export class MyClassComponent implements AfterViewInit {
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
console.log(this.sort); // MatSort{}
}
}
More info on lifecycle hooks here: https://angular.io/guide/lifecycle-hooks.