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

Subash picture Subash · Nov 23, 2017 · Viewed 8.2k times · Source

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

Answer

Karl Johan Vallner picture Karl Johan Vallner · Mar 7, 2018

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.