I have a Angular Material Table. When I surround html for the table with a <div *ngIf="true">
the table renders but the data no longer sorts when clicking on the header column.
Taking the example from: https://material.angular.io/components/table/overview#sorting
And modifying it, just by adding the <div *ngIf="true"> ... </div>
demonstrates this behavior. Example is at: https://stackblitz.com/edit/angular-quzvjv
Thanks Danil, your suggestion worked, but only when the *ngIf evaluated to true when the view of initialized.
The solution I am now using is:
This was based on information from: Angular 2 @ViewChild in *ngIf
Full working solution at: https://stackblitz.com/edit/angular-quzvjv-jzdbb6
Base on the solution Angular 5 Material Data Table sorting not working
In Angular 8, the
@ViewChild
decorator need a second argument{static: true|false}
In order to catch
MatSort
component after DOM rendered, set{static:false}
:When set
{static : true}
, Angular Compiler consider this@ViewChild
element is static, so it only obtain the element one time atngOnInit()
. Even if*ngIf
triggered still can't catch theMatSort
component.See https://stackoverflow.com/a/56359612/11777581 by @PierreDuc
Do the console log in
ngOnInit
ofthis.sort
Angular didn't catch
MatSort
component as on init phase NgIf didn't process the template.Change
ngOnInit
tongAfterViewInit
and it will work as expected.