Angular Material Table Sorting - Data Doesn't

2019-08-24 02:56发布

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

3条回答
forever°为你锁心
2楼-- · 2019-08-24 03:13

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:

@ViewChild(MatSort) set content(sort: MatSort) {
    this.dataSource.sort = sort;
}

This was based on information from: Angular 2 @ViewChild in *ngIf

Full working solution at: https://stackblitz.com/edit/angular-quzvjv-jzdbb6

查看更多
祖国的老花朵
3楼-- · 2019-08-24 03:14

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}:

export class TableSortingExample{

    sort;
    @ViewChild(MatSort, {static: false}) set content(content: ElementRef) {
        this.sort = content;
        if (this.sort){
           this.dataSource.sort = this.sort;
        }
    }
}

When set {static : true}, Angular Compiler consider this @ViewChild element is static, so it only obtain the element one time at ngOnInit(). Even if *ngIf triggered still can't catch the MatSort component.

See https://stackoverflow.com/a/56359612/11777581 by @PierreDuc

查看更多
神经病院院长
4楼-- · 2019-08-24 03:28

Do the console log in ngOnInit of this.sort

Angular didn't catch MatSort component as on init phase NgIf didn't process the template.

Change ngOnInit to ngAfterViewInit and it will work as expected.

查看更多
登录 后发表回答