在代理调用后在代码中设置 MatSort 的排序会导致 ExpressionChangedAfterItHasBeenCheckedError

Gyb*_*lle 4 sorting typescript angular

我想在重新加载数据后保留表的排序设置。我尝试通过在调用代理后触发代码中的排序来做到这一点:

this.keptSort = 'name',
this.keptSortDirection = 'desc',
this.someProxy
    .getTableContent(this.id)            
        .subscribe((res) => {
            const rows = res.map((r) => new RowMode(r)); 
            this.dataSource = new MatTableDataSource(rows);
            this.selectRowsWithId(this.selection);
            if (this.sort) {
                this.sort.sort(<MatSortable>{ 
                   id: this.keptSort, 
                   start: this.keptSortDirection});
            }
});
Run Code Online (Sandbox Code Playgroud)

我的 html 表格是这样的:

<table
    mat-table                    
    matSort
    [dataSource]="dataSource"
    matSortActive="creationDate"
    matSortDirection="desc" >
...</table>
Run Code Online (Sandbox Code Playgroud)

但这会导致错误:

错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。先前值:“活动:未定义”。当前值:“活动:假”。看起来视图是在其父级及其子级经过脏检查后创建的。

额外信息,我还有一个 MatSort 设置器:

@ViewChild(MatSort) set matSort(ms: MatSort) {
    if (ms) {
        this.sort = ms;
        this.setDataSourceAttributes();
    }
}
Run Code Online (Sandbox Code Playgroud)

setDataSourceAttributes() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;        
}
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题有什么想法或方向吗?

Gyb*_*lle 6

找到了解决方法!:D

对于那些有兴趣的人:

我从代理的订阅中删除了“if (this.sort) { ... }”部分。

然后我更改了表 html,现在使用函数来定义排序:

<table
    mat-table                    
    matSort
    [dataSource]="dataSource"
    [matSortActive]="getActiveSort()"
    [matSortDirection]="getSortDirection()" >
...</table>
Run Code Online (Sandbox Code Playgroud)

这些函数返回所需的排序设置。