[Fixed] Unable to select the records across all pages in Angular DataTables

Issue

Trying to select the checkboxes across all pages, but If we change the page selected records are not appending to the previous selected records. It takes second page records only. Can any one suggest me how to handle to select the records across all pages.

 checkboxCheckCount(info: any): void {
    var totalamount = 0;
    $("#firstTable input:checked").each(function() {
      if (info.index != "") {
        totalamount += parseFloat(info.index);
      } else {
        totalamount = totalamount;
      }
    });
    $("#idCheckBoxLabel").text(totalamount);
  }

Working Demo

Solution

First, add ChangeDetectorRef dependency to your component.

constructor(private http: HttpClient, private cdRef: ChangeDetectorRef) {}

then add checked property to all persons.

this.persons = response.data;
this.persons.forEach(f => (f.checked = false));

Then implement your checkuncheckall method:

checkuncheckall() {
    const totalChecked = this.persons.filter(f => f.checked).length;
    const target = totalChecked !== this.persons.length;
    this.persons.forEach(f => (f.checked = target));
    this.cdRef.detectChanges();
}

Your rowCallback is no longer needed.

Changed checkboxCheckCount function which will always update dynamically to get total amount.

get checkboxCheckCount() {
    const selectedPersons = this.persons.filter(f => f.checked).map(m => m.id);
    const totalAmount = selectedPersons.length
      ? selectedPersons.reduce((sum, current) => sum + current)
      : 0;
    return totalAmount;
  }

In HTML:

Setting the count:

<div>Count::<span>{{ checkboxCheckCount }}</span><div>

Toggling individual row checkboxes:

<td><input type="checkbox" class="checkboxCls" [value]="person.checked" [checked]="person.checked" name="id" (change)="person.checked = !person.checked"></td>

See working demo at StackBlitz.

Leave a Reply

(*) Required, Your email will not be published