面临的问题是,当我们选中复选框时..只能在数组中选择选中的项目..我已经使用过滤器来实现..但是子数组的过滤器不起作用。能够检查父数组而获得值。.但是对于子数组,所有数组都显示。
此处的组件代码
export class TestingComponent implements OnInit {
checkedList: any=[];
capRat: any=[];
xyzlist = [
{
id: 1,
value: 'option1',
child:[
{
cid: 101,
childname: "ramu"
},
{
cid: 102,
childname: "raghu"
},
{
cid: 103,
childname: "rosy"
},
]
},
{
id: 2,
value: 'option2',
child:[
{
cid: 201,
childname: "somu"
},
{
cid: 202,
childname: "sundar"
},
{
cid: 203,
childname: "suraj"
},
]
},
{
id: 3,
value: 'option3',
child:[
{
cid: 301,
childname: "jaddu"
},
{
cid: 302,
childname: "veeru"
},
{
cid: 303,
childname: "hyder"
},
]
}
];
a: any=[];
fArr: any=[];
constructor() {
this.a = this.xyzlist.map((el)=>{
let child = el.child.map(cel=>({...cel, checked:false}));
return {...el, checked: false, child}
})
console.log(this.a);
//this.capRatTest();
}
ngOnInit() {
}
// capRatTest(){
// this.capRat=this.xyzlist
// }
onCheckboxChange(option, event) {
// if(event.target.checked) {
// this.checkedList.push(option.id);
// } else {
// for(var i=0 ; i < this.xyzlist.length; i++) {
// if(this.checkedList[i] == option.id){
// this.checkedList.splice(i,1);
// }
// }
// }
option.checked = !option.checked;
option.child.forEach(el=> {
if(option.checked){
el.checked = true
} else{
el.checked = false
}
})
this.filterArr()
}
onCheckboxChildChange(option, event) {
option.checked = !option.checked
this.filterArr()
}
filterArr(){
this.fArr = this.a.filter(el=>{
console.log(el);
let child1 = el.child.filter(el_ => el_.checked == true);
el = {...el, child1};
return el.checked == true;
});
console.log(this.fArr);
}
}
HTML Code Here
<body>
<div class="checkbox" *ngFor="let list of a">
<ul>
<label>
<input type="checkbox" value="{{list.id}}" [checked]="list.checked" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
<li>
<label *ngFor = "let item of list.child">
<input type="checkbox" value="{{item.id}}" [checked]="item.checked" (change)="onCheckboxChildChange(item,$event)">{{item.childname}}</label>
</li>
</ul>
</div>
</body>
答案 0 :(得分:0)
我必须做很多更改才能实现您想要的。
如下更改您的onCheckboxChildChange()
方法。
onCheckboxChildChange(option, event) {
option.checked = !option.checked
if (option.checked) {
let parent = this.a.filter(p => {
let child = p.child.filter(c => {
return c.checked === true;
});
return child.length > 0 ? true: false;
});
parent[0].checked = true;
}
this.filterArr()
}
要filterArr()
,您需要同时使用forEach
和filter
。
filterArr(){
this.fArr = []
this.a.forEach(parent => {
if (parent.checked) {
let tempParent = {...parent};
let tempChild = tempParent.child.filter(c => {
return c.checked === true;
});
tempParent.child = tempChild;
this.fArr.push(tempParent)
}
});
// Chage fArr to [] if there is not any checkbox is checked
let tempArr = this.a.filter(p => p.checked === true);
if (tempArr.length === 0) {
this.fArr = []
}
console.log(JSON.stringify(this.fArr, null, 2));
}
希望这就是您所期望的。找到Stackblitz Example Here.