角度材料表排序 - 数据在 *ngIf 条件内不排序 [英] Angular Material Table Sorting - Data Doesn't sort when inside a *ngIf condition

查看:25
本文介绍了角度材料表排序 - 数据在 *ngIf 条件内不排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

以来自:https://material.angular.io/components/为例表格/概览#sorting

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

And modifying it, just by adding the <div *ngIf="true"> ... </div> demonstrates this behavior. Example is at: https://stackblitz.com/edit/angular-quzvjv

推荐答案

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

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

In Angular 8, the @ViewChild decorator need a second argument {static: true|false}

为了在DOM渲染后捕获MatSort组件,设置{static: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;
        }
    }
}

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

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.

请参阅@PierreDuc 的https://stackoverflow.com/a/56359612/11777581

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

这篇关于角度材料表排序 - 数据在 *ngIf 条件内不排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆