How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output). The current issue is that when I deselect a checkbox on the page and then click submit, it returns an empty array. In my project, the checkboxes may be all pre-selected, some selected and some unselected, or all unselected based on certain conditions. I need to capture the selected and unselected values (same as the desired output) upon submission.

app.component.html

 Checkbox - 
    <div class="col-md-3" id="leftNavBar">
      <ul *ngFor="let item of nestedjson">
        <li class="parentNav">{{item.name}}</li>
        <li class="childData">
          <ul>
            <li *ngFor="let child of item.value; let i = index">{{child}}<span class="pull-right"><input checked type="checkbox" (change)="item.checked[i] = !item.checked[i]" ></span></li>
          </ul>
        </li>


      </ul>


      <div><button type="submit" (click)="getit()">submit</button></div>
    </div>

app.component.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  data: any;
  nestedjson: any;
  message = "";
  test: any;
  constructor() {}

  ngOnInit() {
    this.nestedjson = [
      { name: "parent1", value: ["child11", "child12"] },
      { name: "parent2", value: ["child2"] },
      { name: "parent3", value: ["child3"] }
    ];

   this.nestedjson.forEach(
      v => (v.checked = Array(v.value.length).fill(true))
    );
  }
  getit() {
    var duplicatePushArray = [];

    this.nestedjson.forEach(item => {
      let checked = [];
      item.checked.forEach((isChecked, i) => {
        if (isChecked) {
          checked.push(item.value[i]);
        }
      });
      if (checked.length > 0) {
        duplicatePushArray.push({
          name: item.name,
          value: checked
        });
      }
    });
    console.log("Final Array: ", duplicatePushArray);
  /*  output: [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}]*/
  }
}

Answer №1

<input type="checkbox" [checked]="item.checked[i]" (change)="item.checked[i] = $event.target.checked">

or consider using template forms for your checkboxes

<input type="checkbox" [name]="'checked_' + i" [(ngModel)]="item.checked[i]">

Don't forget to include the forms module in your project

Check out this reduce function that filters values based on checkbox statuses and creates a new object with the results:

getit() {
  var filteredArray = this.nestedjson.reduce((results, item) => {
    const checked = item.value.filter((value, index) => item.checked[index]);
    if (checked.length) {
      results.push({ name: item.name, value: checked });
    }
    return results;
  }, []);
  console.log("Filtered Array: ", filteredArray);
}

For a live example, view the updated StackBlitz demo 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

FNS Date-Timezone Abbreviation

Is there a way to shorten the Australian Eastern Daylight Time abbreviation to just AEDT? When I use it currently, it displays as 11/11/2022 15:29:25 Australian Eastern Daylight Time. I would like it to show as 11/11/2022 15:29:25 AEDT import { formatInT ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...

Dynamically load components within a modal window

I am looking for a way to dynamically load a custom component inside a modal while keeping it as flexible as possible. Here is an example : -HTML CODE- <button id="floating_button" class="floating_button animation_floating_in" (click)="loadCustomComp ...

Exploring the visitor design pattern with numerical enumerated types

I am exploring the use of the visitor pattern to ensure comprehensive handling when adding a new enum value. Here is an example of an enum: export enum ActionItemTypeEnum { AccountManager = 0, Affiliate = 4, } Currently, I have implemented the fol ...

Utilizing ReactJS and Gatsby Js: How to pass the value of a child component to the parent component to create a button

In my current project, I am facing an issue with a simple component that is supposed to pass back the link value from the child component to a function in the parent component. However, it seems to only call back the full function instead of its actual v ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

Ways to utilize a single node_modules folder across multiple projects

Is there a simple method to centralize and share one node_modules folder among all Angular projects, thereby preventing the need to download the same dependencies each time we start a new project? If so, is this approach recommended (what are the pros and ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...

Can an inline try be implemented without including a catch block as demonstrated?

I have a scenario where I need to execute code that may result in an error without catching it. If the response is not valid JSON, then the desired outcome should be 0: Here is the code snippet I am considering: var overallProgress = try {JSON.parse(text ...

Crafting a Visual Storybook with Express.js

I am currently working on developing a photo album app using MEVN. In this project, the value of req.body.ALBUM is used as the folder name and req.body.DESCRIPTION is designated for describing the content. The issue I have encountered so far is that whil ...

Object autofill - Typescript utilizing Angular 5

I am working with an object called "features." Here is an example of the object: [{"_id":"5af03d95c4c18d16255b5ac7","name":"Feature 1","description":"<p>Description</p>\n","neworchange":"new","releaseId":"5aead2d6b28715733166e59a","produc ...

When the same component is conditionally rendered, it does not activate the mounted() hook

I am new to Vue and eager to learn. I am attempting to conditionally render a component like so: <div> <Map v-if="bool" mapSrc="src1.jpg" :idList="idList1" :data="dataVariable1"></Map> <Map v-else mapSrc="src2.jpg" :idList="idList ...

Establishing a connection between TypeScript and MongoDB

Whenever I try to add the mongo connection to the request, I encounter an error. The error message says: 'Property 'dbClient' does not exist on type 'Request<ParamsDictionary>'. I want the connection to be accessible witho ...

Struggling to apply the active class using a combination of jquery, nodejs, express, and bootstrap

I've been working on an express generator Node.js application that uses Bootstrap and Jade. I'm facing issues with setting the active state of the navigation bar. After trying to implement some jQuery, I noticed that when I click on the nav bar, ...

Issue with AngularJS: Local storage not saving updated contenteditable data

My local storage implementation stops working when I attempt to incorporate contentEditable feature. Here is the link to the CodePen for reference: https://codepen.io/zanderbush/pen/WNwWbWe. Any assistance would be greatly appreciated. The functionality w ...

Locate a specific item in an array using AngularJs based on a key and present its value on the View

Imagine you have an array of objects: $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}]; And a variable that corresponds to key. For instance: $scope.a = 3; In the Controller, you want ...

Error: Property 'instance' is undefined and cannot be read

Trying to confirm the functionality of the following method: showSnackbar(): void { if (this.modifiedReferences.length) { const snackbar = this.snackbarService.open({ message: '', type: 'success', durat ...

What precautions can I take to safely and securely extend event handling?

I am currently developing a small JavaScript library that includes components requiring "messages" based on specific page events, which allow users to define response functions. I need to access general events like onkeydown and let users determine how eac ...