我正在使用 ngx-datatable 列出一些我想使用函数调用选择所有行的用户。有什么办法吗?我正在使用角度 4
3 回答
编辑 1
我的旧答案有一些负面影响,我花了一些时间来挖掘更多。据我了解,由于您只能勾选标题中的全选按钮,因此 DatatableComponent 下有一个 onHeaderSelect() 函数,如果我们从外部触发它,它的作用是单击全选复选框。
代码如下。
export class DatatableVerticalComponent implements OnInit {
public rows = [{prop1:1, prop2:2},{prop1:3, prop2:4}];
@ViewChild(DatatableComponent) ngxDatatable: DatatableComponent;
onSelectAllClick() {
this.ngxDatatable.onHeaderSelect(true);
}
}
旧答案
由于我删除了标题行,因此无法使用默认复选框功能
http://swimlane.github.io/ngx-datatable/#chkbox-selection
我做了一个快速的解决方法,从 ngx-datatable 之外选择所有行。
代码:
export class DatatableVerticalComponent implements OnInit {
public rows = [{prop1:1, prop2:2},{prop1:3, prop2:4}];
@ViewChild(DatatableComponent) ngxDatatable: DatatableComponent;
onSelectAllClick() {
this.ngxDatatable.selected = this.rows;
}
}
解释:
首先,您在 component.ts 文件中将其作为 ViewChild。现在 ngx-datatable 将选定的行保留为数组
/**
* List of row objects that should be
* represented as selected in the grid.
* Default value: `[]`
*/
@Input() selected: any[] = [];
由于我没有在 DatatableComponent 中找到设置选定行的函数,所以我只是使用 ViewChild 来设置选定变量。我没有使用 [@Input] 创建数据绑定,因为我不想给人留下我一直在控制来自外部代码的选择的印象。
假设您将用户存储在users
道具中,您需要将selected
输入道具添加到模板中的表格中,如下所示:
<ngx-datatable [rows]="users" [selected]="selectedUsers">...
之后,您应该能够选择组件逻辑中的所有用户,如下所示:
@Component()
export class UsersComponent {
users: any[];
selectedUsers: any[];
/* ... */
selectAllUsers(): void {
this.selectedUsers = [...users];
}
}
请注意,这种方法非常简化,只是为了让您了解可能的解决方案可能是什么样子。这意味着它还没有经过测试,所以让我知道它是否有效。
这是一个老问题,但我遇到了同样的问题,并认为分享我的解决方案会有所帮助。
基于 ngxdatatable 的代码(github 源- 我添加了代码段以及链接可能会因代码更改而过时):
/**
* Toggle all row selection
*/
onHeaderSelect(event: any): void {
if (this.selectAllRowsOnPage) {
// before we splice, chk if we currently have all selected
const first = this.bodyComponent.indexes.first;
const last = this.bodyComponent.indexes.last;
const allSelected = this.selected.length === last - first;
// remove all existing either way
this.selected = [];
// do the opposite here
if (!allSelected) {
this.selected.push(...this._internalRows.slice(first, last));
}
} else {
// before we splice, chk if we currently have all selected
const allSelected = this.selected.length === this.rows.length;
// remove all existing either way
this.selected = [];
// do the opposite here
if (!allSelected) {
this.selected.push(...this.rows);
}
}
this.select.emit({
selected: this.selected
});
}
onHeaderSelect 切换所有行选择,这不是我需要的。
我需要选择所有行。
因此,受代码源的启发,我刚刚在我的组件中编写了以下方法:
@ViewChild(DatatableComponent) ngxDatatable: DatatableComponent;
...
unselectRows(): void {
const table = this.ngxDatatable;
const allSelected = table.selected.length === table.rows.length;
if (!allSelected) { // Select all only if not already the case
// Reset the selection first
table.selected = [];
// Add all rows to the selection
table.selected.push(...table.rows);
// Important: Emit the select event
table.select.emit({
selected: table.selected
});
}
}
该解决方案适用于我的用例。
注意:我不使用selectAllRowsOnPage
可能会导致我在这里没有处理的问题。