Search code examples
angularcheckboxdata-bindingcheckedarray-splice

A row is removed when uncheck a checkbox after checked all the check boxes


I have a check box column in a table in angular.

when check all, all are checked (that's working fine).

when uncheck all, all are unchecked (that's working fine).

if check one, the particular check box is checked, if uncheck the checked checkbox, unchecked. (working fine)

But I am facing and issue, when I try to uncheck a check box after checked all the check boxes, the row is removed instead of unchecking the check box. ie: this.holidays array also changed when unchecking a checkbox after checked all the check boxes.

Why this issue is occur?

This is my custom table

  <ngx-custom-table *ngIf="paginationLoad || selectedItems" 
    #table
      [value]="holidays"
      [selectedItems]="selectedItems"        
    >

 <ng-template  #header let-columns>
        <tr>
          <th >
             <nb-checkbox (checkedChange)="OnCheckBoxchangeAll(holidays)"></nb-checkbox>
          </th>
         // removed rest of the columns
        </tr>
      </ng-template>
      <ng-template #body  let-data>
        <tr>
          <td>
            <nb-checkbox (checkedChange)="OnCheckBoxchange(data ,$event)" [checked]="selectedItems.indexOf(data) >=0" ></nb-checkbox>
          </td>
 // removed rest of the columns
 </tr>
      </ng-template>
    </ngx-custom-table>
  OnCheckBoxchange(data, isChecked: boolean){
    console.log(data);

    if(isChecked === true){
      this.selectedItems.push(data);
    }
    else{
      this.selectedItems.splice(this.selectedItems.findIndex(x => x.id === data.id) , 1);
    }  
    console.log("this.selectedItems" , this.selectedItems);
    console.log("this.holidays" , this.holidays); 
// here the data is removed from this.holidays too. Why? 
  }

  OnCheckBoxchangeAll(data){
    this.checkedAll = !this.checkedAll;

    if(this.checkedAll === true) {
      this.selectedItems = data;
    }
    else {
      this.selectedItems = [];
    }
}

this.holidays is fetched from API


Solution

  • In OnCheckBoxchangeAll(data) you need to change as follows:

    if (this.checkedAll === true) {
      this.selectedItems = [...data];
    }
    

    So the 2 arrays do not point to the same memory address but are managed as 2 separate arrays.

    Otherwise, the following:

    this.selectedItems.splice(this.selectedItems.findIndex(x => x.id === data.id) , 1);
    

    causes the original data to change as well.