@Viewchild can not see matSort

Luiz Ricardo Cardoso picture Luiz Ricardo Cardoso · Mar 16, 2018 · Viewed 9.6k times · Source

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.

Answer

vince picture vince · Mar 16, 2018

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.