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
CodePudding user response:
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 manage 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.