Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Viewchild can not see matSort

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.

like image 607
Luiz Ricardo Cardoso Avatar asked Mar 16 '18 00:03

Luiz Ricardo Cardoso


1 Answers

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.

like image 58
vince Avatar answered Oct 28 '22 07:10

vince