使用服务器端分页时,如何在Angular Material 2 mat-table上实现跨页选行?
我有一个可以使用服务器端分页的 Angular Material 表。然而,默认的实现(正如Material文档中所描述的那样)在导航到一个新的页面时,会取消选中所有的行(以及 "选择所有行 "复选框)。
我尝试了各种各样的方法(太多了,无法在此记录),但这里有一些片段可能会有帮助。为了清晰起见,代码已被简化。
selections.selected数组确实包含了跨页的所有选择行。通过将默认的isSelected函数改成自定义函数--跨页的行会显示为选中。注意,在我的例子中,行有一个唯一的属性_id。
private isSelectedCustom(row: any): boolean {
return <boolean>this.selection.selected.find(o => o._id === row._id);
}
selection.isSelected = isSelectedCustom.bind(this);
然而,如果我取消选中某行(导航到一个新的页面并回来),该行又显示为选中。我不清楚为什么,而且当我取消选中行和在页面之间导航时,我甚至在selection.selected中看到了重复的行。
试图从select中手动删除行(和重复的行)并没有成功,即
selection.onChange.subscribe(selection => {
if (selection && selection.removed && selection.removed[0] && selection.removed.length == 1) {
let removeId = selection.removed[0]._id;
// Remove multiple occurences. Unknown how selection.selected can have duplicates.
for (var i = this.selection.selected.length - 1; i >= 0; i--) {
if (this.selection.selected[i]['_id'] == removeId) {
console.log('force remove', this.selection.selected[i]);
//this.selection.selected.splice(i, 1);
this.selection.selected.
}
}
}
}
对于 "select all rows "复选框,无法推导出是否所有行都被选中(因为客户端只有一页的行而不是所有行)。所以我使用了一个flag,当 "select all rows "被checkunchecked时,这个flag被显式地设置为truefalse。
当导航到后续页面时,如果 "select all rows "标志为真,那么我就将所有行设置为checked。
dataSource.data.forEach(row => selection.select(row));
如果某行未被选中,我将 "选择所有行 "标志设置为false。
if (selection && selection.removed && selection.removed.length > 0) {
isAllPagesSelected = false;
}
这种 "选择所有行 "复选框的方法似乎一般都能用,但感觉很乱。
如果没有跨页,它就容易多了,但是
onPageChanged ->加载新的数据 ->从viewChild->foreach find row ->为每行设置checkuncheck(包括theader中的checkAllbox)。
也许需要viewChild forEach row => 找到最近的checkbox并设置Checked。