Html 如何将选中的多个选中值放入对象数组
我有一些来自循环的复选框,我需要在单击“提交”时捕获选定/预选值,并将其转换为以下格式 我已经得到了这些值,但在检查后,点击提交按钮,但这里我需要的是得到值,已经检查提交按钮。下面是代码 app.component.html 试着这样做:Html 如何将选中的多个选中值放入对象数组,html,angular,typescript,Html,Angular,Typescript,我有一些来自循环的复选框,我需要在单击“提交”时捕获选定/预选值,并将其转换为以下格式 我已经得到了这些值,但在检查后,点击提交按钮,但这里我需要的是得到值,已经检查提交按钮。下面是代码 app.component.html 试着这样做: getit() { var duplicatePushArray = []; this.nestedjson.forEach(item => { console.log(item); let checke
getit() {
var duplicatePushArray = [];
this.nestedjson.forEach(item => {
console.log(item);
let checked = [];
item.checked.forEach((isCkecked, i) => {
if (isCkecked) {
checked.push(item.value[i]);
}
});
if (checked.length > 0) {
duplicatePushArray.push({
name: item.name,
value: checked
});
}
});
console.log("Final Array: ", duplicatePushArray);
}
有正式的安排。检查此示例:我们不能用现有代码修复吗,如果我使用反应式表单,我需要更改整个代码。我的代码已经在运行,但选中了复选框。如果它被预选了,它的显示空值。你能显示预选是如何发生的吗谢谢你在这里的回答预选复选框值为空数组我尝试了此代码
<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 type="checkbox" (change)="item.checked[i] = !item.checked[i]" checked ></span></li>
</ul>
</li>
</ul>
<div><button type="submit" (click)="getit()">submit</button></div>
</div>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@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(private formBuilder: FormBuilder) {
}
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(false));
}
getit(){
const data = this.nestedjson;
let duplicatePushArray = this.nestedjson.reduce((acc, v) => {
let temp = {name: v.name, value: []};
v.checked.forEach((val, i) => {
if(val){
temp.value.push(v.value[i]);
}
})
if(temp.value.length > 0){
acc.push(temp)
}
return acc
}, []);
console.log('Final Array: ', duplicatePushArray)
/*output: [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}]*/
}
}
getit() {
var duplicatePushArray = [];
this.nestedjson.forEach(item => {
console.log(item);
let checked = [];
item.checked.forEach((isCkecked, i) => {
if (isCkecked) {
checked.push(item.value[i]);
}
});
if (checked.length > 0) {
duplicatePushArray.push({
name: item.name,
value: checked
});
}
});
console.log("Final Array: ", duplicatePushArray);
}