Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make select all row using code in ngx-datatable

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

like image 869
Subash Avatar asked Jan 20 '26 15:01

Subash


2 Answers

Edit 1

My old answer had a few negative side effects and I took time to dig around a bit more. As I understand, since you can only tick a select all button in the header, there is a onHeaderSelect() function under DatatableComponent and if we externally trigger it, it functions as a select all checkbox click.

Code below.

export class DatatableVerticalComponent implements OnInit {

    public rows = [{prop1:1, prop2:2},{prop1:3, prop2:4}];

    @ViewChild(DatatableComponent) ngxDatatable: DatatableComponent;

    onSelectAllClick() {
        this.ngxDatatable.onHeaderSelect(true);
    }

}

OLD ANSWER

Since I removed the header row and thus could not use the default checkbox functionality

http://swimlane.github.io/ngx-datatable/#chkbox-selection

I made a quick workaround to select all rows, from outside of the ngx-datatable.

Code:

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;
    }

}

Explanation:

First you take the as a ViewChild in the component.ts file. Now ngx-datatable keeps the selected rows as an array

/**
   * List of row objects that should be
   * represented as selected in the grid.
   * Default value: `[]`
   */
@Input() selected: any[] = [];

Since I did not find a function to set selected rows in the DatatableComponent, I just used the ViewChild to set the selected variable. I did not create data-binding with [@Input], because I do not want to leave the impression that I am constantly controlling the selection from outside code.

like image 81
Karl Johan Vallner Avatar answered Jan 22 '26 07:01

Karl Johan Vallner


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.

like image 34
Bohdan Khodakivskyi Avatar answered Jan 22 '26 05:01

Bohdan Khodakivskyi