简体   繁体   English

计算用角6选中的复选框数量

[英]Count how many checkboxes are checked with angular 6

Here is my checkboxes which i generate with ngFor 这是我用ngFor生成的复选框

<div *ngFor="let check of feature.tests; let i = index" class="col-md-12">
    <mat-checkbox [checked]="i <= map[l][k]" [(ngModel)]="check.checked"
                  (change)="checkAll($event.checked, i ,k,  l)"
                  (ngModelChange)="changed(i)">{{check.name}} - {{feature.type}}
    </mat-checkbox>
</div>

when i click a checkbox, all the checkboxes with inferior index are checked as well and the checkboxes with superior index are unchecked 当我单击一个复选框时,所有具有较低索引的复选框也会被选中,而具有较高索引的复选框则未被选中

when i click here check1 it do that check2 当我单击此处check1时 ,执行该check2

so my counter should be at 2 with only 1 click 所以我的柜台应该是2点,只有1次点击

here the function that i use for check the checkboxes with previous indexes 这是我用来检查带有先前索引的复选框的功能

checkAll(c, i: number, k, l) {
  if (c) {
    this.map[l][k] = i;
  } else {
    this.map[l][k] = i - 1;
  }
}

i would like to count how many checkboxes are checked and display the result in my HTML template, how could i achieve this ? 我想计算选中了多少复选框并在我的HTML模板中显示结果,我怎么能做到这一点?

I have faced the same problem. 我也遇到过同样的问题。 I hope the following solution will help you 希望以下解决方案对您有所帮助

You can trigger the event whenever checked or unchecked the box like bellow 您可以在选中或取消选中以下复选框时触发事件

 <input type="checkbox" class="form-check-input" id="exampleCheck2" (change)="checkBox($event);">

And call in ts file like bellow and you can modify it as per your requirement. 并像下面这样调用ts文件,您可以根据需要对其进行修改。

checkBox(enent){
     this.counter++; // counter is the varible
     if(this.counter%2==1){
       this.checked= true; //checked is the variable
    }
    else{
      this.checked=false;
     }
  }

What if you put the checkboxes into a form anfd then subscribe to their valuechanges like this: 如果将复选框放入表格anfd然后订阅它们的值更改,该怎么办:

html is the same but wrap it around with a form tag like this: html相同,但是用如下形式的标签将其包裹起来:

<form [formGroup]="form">
...
</form>

ts: ts:

form: FormGroup;
count=0
this.form.valueChanges.subscribe(()=>{
   for(let i=0; i<this.form.value.length; i++){
      if(this.form.value[i]==true){
       count++
      }
 }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM