When all the checkboxes have been checked and then one is unchecked, a row is consequently removed

In my Angular table, I have a checkbox column.

When I check all checkboxes, they all get checked as expected.

Similarly, when I uncheck all checkboxes, they all get unchecked properly.

If I check just one checkbox, only that particular one gets checked, and if I then uncheck it, it becomes unchecked - this functionality is working correctly.

However, I am encountering an issue where, if I try to uncheck a checkbox after having checked all the checkboxes, instead of simply unchecking the box, the entire row is removed. i.e., the 'holidays' array also gets modified when trying to uncheck a checkbox after checking all of them.

Why is this issue happening?

This is the structure of my customized 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>
         // remaining columns are omitted for brevity
        </tr>
      </ng-template>
      <ng-template #body  let-data>
        <tr>
          <td>
            <nb-checkbox (checkedChange)="OnCheckBoxchange(data ,$event)" [checked]="selectedItems.indexOf(data) >=0"></nb-checkbox>
          </td>
 // remaining columns are omitted for brevity
 </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 also being removed from this.holidays. Why? 
  }

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

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

The data in this.holidays is fetched from an API.

Answer №1

To ensure that OnCheckBoxchangeAll(data) functions correctly, make the following adjustments:

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

This will prevent the two arrays from sharing the same memory address and instead manage them as separate entities.

Otherwise, using the code snippet:

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

can inadvertently alter the original data object as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble locating node_modules post deployment?

Although the title may lead you astray, please stay with me for a moment. I've created a basic Angular2 application in Visual Studio 2015 and have now deployed it to Azure. While having node_modules in the development environment worked perfectly fi ...

Display only months and years in the NgbDatepicker

Struggling with configuring the NgbDatepicker directive in my Bootstrap 4 and Angular 4 powered app. I only want to display months and years, similar to credit cards. Selecting a specific day is not important to me, I just need to choose the month and yea ...

What is the best method for consistently populating data in an Angular application?

After successfully retrieving data from the backend and displaying it on the frontend in my application, I encountered a scenario where sometimes the data is not visible when navigating from other pages. A manual refresh of the page is required to display ...

Frontend Development with Angular 7+: A Modular Approach

I'm aiming to develop a frontend application that is modularized, allowing for the release of each module independently. However, I've run into an issue where creating angular modules for each frontend module requires building all modules togeth ...

Is it feasible to use Angular 2 in conjunction with local storage and JWT implementation on IE9 and

Could someone please advise me on how to implement local storage in Angular2 for IE9 and above? I've attempted following this guide https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.h42z63t9v, but my Angular 2 applicati ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

What are some best practices for integrating ES2020 into an Angular project?

Below is the content of my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap&q ...

Issue with ngmodel causing placeholder in Angular 2 md-input to not move up

While working with Angular Material to style an input field, I noticed that the placeholder does not move up when there is a value in the input. This behavior occurs only when using ngModel to bind the input. Interestingly, clicking on the input causes the ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Is it possible to pass multiple parameters in Angular by utilizing the click() function?

Is there a method for passing parameters with click() in Angular? <a asp-action="CreateSales" (click)="CreateSales(productname='pa', price='16.5')">Some Text</a> I am still learning Angular and would appreciat ...

How to retrieve the displayed text of a selected option in an Angular 7 reactive form dropdown control instead of the option value

Is there a way to retrieve the displayed text of the selected value in a drop-down list instead of just the value when using reactive forms? This is my current script: <form [formGroup]="formGroup" formArrayName="test"> <ng-container matColu ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

angular overlapping collapsing

Currently, I am developing a chat board application where users can leave comments under each post. I am in the process of creating a button that will collapse all the comments for better visibility, especially as they continue to grow. <div id="collap ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

Experiencing the error "f.ngOnChanges is not a function in target es5" while using Angular4

Encountering an issue f.ngOnChanges is throwing an error The problem arises when my tsconfig.json file is configured to target es5. However, everything works fine if I set the target to es6. Is there a way to make ngOnChange function properly with es ...

Exploring deep levels of nested FormArrays with Angular 2 and FormBuilder

Currently diving into Angular 2, I am embarking on the challenge of constructing a nested form, validating it, and adding new objects Projects to object GroupProject. Here is a snippet from my TypeScript file: ngOnInit() { this.myForm = this. ...