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"]}]*/
}
}