I am using ngx-datatable for listing some users I would like to select all rows using a function call. Is there any way ? I am using angular 4
I am using ngx-datatable for listing some users I would like to select all rows using a function call. Is there any way ? I am using angular 4
Assuming you have your users stored in users prop, you'll need to add selected input prop to your table in template like this:
<ngx-datatable [rows]="users" [selected]="selectedUsers">...
After that, you should be able to select all users in your component logic like this:
@Component()
export class UsersComponent {
users: any[];
selectedUsers: any[];
/* ... */
selectAllUsers(): void {
this.selectedUsers = [...users];
}
}
Please note this approach is very simplified just to give you an idea of what possible solution might look like. That means it hasn't been tested, so let me know if it worked.
It is an old question, but I had the same issue and think sharing my solution could help.
Based on the code of ngxdatatable (github source - I add the snippet as well as the link may become obsolete with code changes):
/**
* 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
});
}
The onHeaderSelect toggles all row selection which is not what I need.
I need to select all rows.
Therefore, inspired by the code source I just wrote the below method in my component:
@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
});
}
}
This solution works fine for my use case.
Note: I do not use selectAllRowsOnPage which may induce issue(s) I did not handle here.