角度材料表排序 - 数据在 *ngIf 条件内不排序

Tho*_*cke 0 angular-material angular angular-material-table

我有一个角度材料表。当我用 html 包围表格时<div *ngIf="true">,表格会呈现,但单击标题列时数据不再排序。

以以下示例为例:https : //material.angular.io/components/table/overview#sorting

并修改它,只需添加<div *ngIf="true"> ... </div>演示此行为。示例位于:https : //stackblitz.com/edit/angular-quzvjv

小智 5

基于解决方案Angular 5 Material Data Table 排序不起作用

在 Angular 8 中,@ViewChild装饰器需要第二个参数{static: true|false}

为了MatSort在 DOM 渲染后捕获组件,请设置{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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当 set 时{static : true},Angular Compiler 认为这个@ViewChild元素是静态的,所以它只在 处获取该元素一次ngOnInit()。即使*ngIf触发仍然无法捕捉到MatSort组件。

请参阅@PierreDuc 的/sf/answers/3945172871/