Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array.

The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array.

Does anyone know how to efficiently remove the object from the array when the checkbox is unchecked?

Here is the HTML code:

<div *ngFor="let item of order; let i = index">
  <input type="checkbox" [id]="item+i" [name]="item"[(ngModel)]="item.Checked" (change)="getCheckboxValues(item)">
   <label [for]="item+i"> {{item}} </label>
</div>

And here is the TypeScript code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  order = ['One','Two','Three','Four'];

  newArray : any = [];

  //Function to detect Checkbox Change
  getCheckboxValues(data) {
    let obj = {
      "order" : data
    }

    // Adding the object to the array
    this.newArray.push(obj);

    //The issue occurs when unchecking - How do we remove the value from the array when it's unchecked?
    console.log(this.newArray);
  }

}

You can find my progress on solving this issue at this link.

Could someone please assist me in removing unchecked values from the `newArray`?

Answer №1

Make a switch to

(ngModelChange)="updateCheckboxItems($event,item)"

Modify the function to include adding if not present and removing if already there depending on checkbox state

  //Function for detecting checkbox changes
  updateCheckboxItems(event, item) {
    let object = {
      "order" : item
    }

    if(event.target.checked){
      // Adding the object to an array
      this.updatedArray.push(object);

    } else {
      let removeIndex = this.updatedArray.findIndex(item => item.order === data);

      if(removeIndex !== -1)
        this.updatedArray.splice(removeIndex, 1);
    }

    //Avoids duplication when unchecking
    //How to eliminate value from array when unchecked
    console.log(this.updatedArray);
  }

Link to example https://stackblitz.com/edit/angular-5jamcr

Answer №2

To remove an object from the array if its checked status is false, pass the index along with the object.

//Checkbox Change detecting function
 getCheckboxValues(data, index) {
    let obj = {
      "order" : data
    }

    if(!data.Checked){
       this.newArray.splice(index, 1);
    }
    else{

      // Adding the object to the array
      this.newArray.push(obj);
    }


       // Duplicates the object if unchecked
       // Removing value from array on unchecking
        console.log(this.newArray);
}

<input type="checkbox" [id]="item+i" [name]="item"[(ngModel)]="item.Checked" (change)="getCheckboxValues(item, i)">

Answer №3

Give this code a try:

Update in your HTML file:

(ngModelChange)="getCheckboxValues($event,item)"  // utilize ngModelChange event

and in the TypeScript file:

getCheckboxValues(event, data) {

    // using findIndex method to locate the index of checked or unchecked item
    var index = this.newArray.findIndex(x => x.order==data);

    // If the item is checked, add it to the array
    if (event) {
       let obj = {
        "order": data
    }
      // Adding the object to the array
      this.newArray.push(obj);
    }
    else {
      this.newArray.splice(index, 1);
    }
    //Removing the object from the array if it was previously added and then unchecked
    console.log(this.newArray);
}

View the live example on StackBlitz

You can learn more about the findIndex and indexOf methods here

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

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

Unable to locate the specified nested module during the import process

Imagine a scenario where we have two packages, namely package1 and package2. When package2 attempts to import the module from package1, an error is thrown stating that the module is not found. The import statement in question looks like this: import { ... ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...

Angular - optional parameter in route using ngRouter

I have a question regarding using Angular (4) with the @angular/router. I want to be able to include optional parameters in a path style, but am facing some challenges. Currently, my code looks like this: { path: 'cars', component: CarComponent ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

Utilizing Angular resolver to inject the router functionality

In my Angular (v13) application, I have defined a resolver to interact with a Wordpress backend. The purpose of this resolver is to determine the post type and ID from Wordpress when a user accesses a URL, and then route accordingly (to a post list, single ...

What's the deal with this route being a 404 error?

I'm currently working on incorporating a new route into Express, specifically for handling 404 errors. Despite my efforts to configure the route in a similar manner to others, I am encountering some difficulties. var repomapRouter = require('./ ...

What is the best way to add a listener for a modification of innerHTML within a <span>?

How can I detect changes inside a particular <span> element in order to attach a handler, but so far have been unsuccessful? Below is the HTML snippet: <span class="pad-truck-number-position"><?php echo $_SESSION['truckId']; ?> ...

Is it possible to send notifications via email prior to reaching a particular deadline?

I'm trying to figure out a way to notify users one day before dates of events stored in the database. I'm stumped and could really use some help with this. Can someone please assist me? ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Optimizing with react and mobX: What You Need to Know

I am new to React and MobX and have been studying various tutorials on using both together. Currently, I am working on creating a form where users can select a product through autocomplete functionality using react-select. Once a product is selected, the i ...

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

What is the best way to compare JavaScript arrays with the same items but in a different order?

Within my product groups, each group is identified by a set of product_type_ids. I am looking for a way to match different groups based on their product_type_ids. The order of the ids may vary within the group, but as long as the sets of ids match, I cons ...

Rendering components asynchronously in ReactJS

After completing my ajax request, I need to render my component. Here is a snippet of the code: var CategoriesSetup = React.createClass({ render: function(){ var rows = []; $.get('http://foobar.io/api/v1/listings/categories/&apo ...

Using ionic-v4 to browse through a application via its URL pathways

I am facing an issue with navigating to specific pages on my website using the URL. For example, I want to access page 1 by typing in the address bar: localhost:8100/mySite/page1 and go directly to page 1 localhost:8100/mySite/page3 and navigate to pag ...

Utilizing ExtJS and its control feature

I am facing an issue with the following code block: run: function(e, row){ var me = this; var container = Ext.getCmp('centercontainer'); try { container.removeAll(); } catch(e) { } // The code snippet below is act ...