div的复选框计数器



我需要添加三个div,每个div中有多个复选框。我实现了将计数器添加到单个div中选择的复选框中。我想添加一个计数器来记录选中复选框的div。

HTML代码

<div class="container">
<div class="firstCheckbox" (click)="dis2=true">
<div *ngFor ="let o of options" >
<input [disabled]="dis1" type="checkbox" [(ngModel)]="o.checked" (ngModelChange)="changed()">
{{ o.name }}
</div>
<p>Total O-Items Checked :- {{count}}</p>

</div>
<div class="secondCheckbox"  (click)="dis1=true" >

<div *ngFor ="let p of options1" >
<input [disabled]="dis2" type="checkbox" [(ngModel)]="p.checked" (ngModelChange)="changed1()">
{{ p.name }}
</div>
<p>Total P-Items Checked :- {{count1}}</p>

</div>

Component.ts代码

export class CheckComponent implements OnInit {
count: number;
count1: number;
dis1:boolean;
dis2:boolean;

options : any = [
{ id:0 , 
name : 'A' },
{ id:1 , 
name : 'B' },
{ id:2 , 
name : 'C' },
{ id:3 , 
name : 'D' },
{ id:4 ,
name : 'E' },
{ id:5 , 
name : 'F' },
];
options1 : any = [
{ id:0 , 
name : 'A' },
{ id:1 , 
name : 'B' },
{ id:2 , 
name : 'C' },
{ id:3 , 
name : 'D' },
{ id:4 ,
name : 'E'},
{ id:5 , 
name : 'F' },
];
constructor() { }
changed(){
this.count = 0;
this.options.forEach(item => {
if (item['checked']) {
this.count = this.count + 1;
}
})
}

changed1(){
this.count1 = 0;
this.options1.forEach(item => {
if (item['checked']) {
this.count1 = this.count1 + 1;
}
})
}
ngOnInit(): void {
}
}

我想添加一个计数器,这样如果div class="第一复选框">中的复选框,则divCounter=divCounter+1;第二复选框",则divCounter自身递增。基本上是一个外部计数器,它在这个过程中给我一个活动div的计数。

您的代码可以进行重构和优化,但我不打算讨论这个问题。有多种方法可以实现你想要的,我会给你一个我脑海中最快的。您可以使用存储唯一值的Set

get activeDivsCount: number{
return this.activeDivs.size;
}
activeDivs = new Set();
changed(){
this.count = 0;
this.options.forEach(item => {
if (item['checked']) {
this.count = this.count + 1;
}
});
if(this.count > 0)
this.activeDivs.add('div1');
else
this.activeDivs.delete('div1');
}
changed1(){
this.count1 = 0;
this.options1.forEach(item => {
if (item['checked']) {
this.count1 = this.count1 + 1;
}
});
if(this.count1 > 0)
this.activeDivs.add('div2');
else
this.activeDivs.delete('div2');
}

获取div,然后获取其选中的复选框

document.querySelectorAll("div").forEach(function(div) {
div.setAttribute("checkedBoxes", div.querySelectorAll("input[type=checkbox]:checked").length);
});

最新更新