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

Tips for correctly sending the response code from a Node.js API

I have a straightforward node-based API that is responsible for parsing JSON data, saving it into a Postgres database, and sending the correct response code (e.g., HTTP 201). Here is an excerpt of my code: router.route('/customer') .post(fu ...

Is it possible to obtain the socket.id of a user immediately upon their connection?

Does anyone know how I can send a personalized message to a user when they connect, without broadcasting it to everyone else? I'd like to use their socket ID with the code io.to(theirSocketID).emit('chat message', 'Welcome');, but ...

What is the best way to showcase 10 data points from a list of 100 in an Angular datatable?

Is there a way to display the first 10 values from a list of 100 using Angular DataTable? <tr *ngFor="let i of arr"> <td>{{i}}</td> </tr> ...

disallow rowOnClick function in the datatable

I am facing an issue with a t:datatable where the rowOnClick event is being triggered. The problem arises when there is an icon in a column that, when clicked, opens a popup. This action also triggers the rowOnClick event, which I don't want. For this ...

iPhone: Fixed position div disappearing

Currently, I am working on creating a mobile menu for my Joomla 3 site located at . The menu is functioning correctly on desktops, however, when attempting to view it on my iPhone, the menu slides in but remains invisible. Despite this, I can still tap on ...

How does jQuery create a hover effect that changes the background color of a link and keeps it when the mouse hovers over a

I'm attempting to add a background color to the main link that displays a sub-menu. Currently, only the sub-menu is visible, and as soon as the mouse moves away from the main link, the color reverts back to the original background color. <nav& ...

Tips for effectively injecting retrieved API response data into a Table

Creating a google-map with customized markers that are logos of companies is the goal. Obtaining a json file from the APIs containing the vessels of interest has been successful. The challenge faced is injecting these vessels into a table on the user inte ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

Avoid having Masonry load all divs simultaneously

I have experience using jQuery Masonry on Tumblr, but now I want to incorporate it into my portfolio website for displaying my photography. However, I'm struggling to find a solution that allows sets of images to load in as the user scrolls to the bot ...

When the component is reloaded, props will become defined

I am trying to iterate through an object's array to create a table structure like the one below: import React from "react"; export default function Scoreboard(props) { return ( <div className="scoreboard"> <ta ...

Creating a constructor that assigns values by using interfaces that are built upon the class

Looking at this interface/class example export interface MyErrorI { something: boolean; } export class MyError extends Error implements MyErrorI { public something = false; constructor(message: string, key: keyof MyErrorI ) { super(m ...

Swapping out 'useResult' in graphql for Vue and Apollo: A step-by-step guide

I need to replace the useResult function that is fetching data from GraphQL with a computed function. const locationOptions = useResult( result, [], ({ getLocations }): Option[] => formatOptions(getLocations) ) Instead, I want ...

Error encountered following repo duplication

Recently, I upgraded to a new workstation and decided to clone my Angular4 Project repo onto it. After completing the cloning process, I executed: npm install This command is used to fetch all the required node_modules, leading to a multitude of missing ...

When using Javascript, you can expect to receive a modified structure that is different from

I am dealing with an array of objects that have the following structure: const data: [ { id: 21786162, label: "cBTC 2021-06-25 Put $50,000.00", active": true, type: "put", strike_price: 5000000, date_live: "2019-11- ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...

`CSS animation for vanishing line effect`

I want to create an animated logo that gives the illusion of being pulled up by a rope, represented by a vertical black line, from the bottom of the page to the top. As the logo moves upwards, I would like the rope to disappear behind it, but I'm uns ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

I'm looking to enhance my code by adding a new user login password. How can I achieve this?

Currently, I am in the process of adding another user and have been exploring various code snippets available on different websites. I decided to test the following example, which worked perfectly. However, I am now wondering how I can add an additional u ...

Ways to transfer information from the server to the user interface in a WordPress extension

I am currently developing a WordPress plugin and have successfully created a form in the admin panel. Now, I am looking to transfer the data collected from that form to my Frontend JavaScript file. Is there a way to achieve this, and if so, what steps shou ...