如何获取在角度7中选中的多个复选框的计数

我有一些复选框,我需要获取单击按钮时选中的所有复选框的计数,这是下面的代码,我也有

app.component.html

 <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">{{child}}<span class="pull-right"><input type="checkbox"></span></li>
          </ul>
        </li>
      </ul>
<div><button type="submit">Submit</button></div>
    </div>

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "my-app",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent {
  nestedjson = [
    { name: "parent1",value: ["child11","child12"] },{ name: "parent2",value: ["child2"] },{ name: "parent3",value: ["child3"] }
  ];
}
lantianniu 回答:如何获取在角度7中选中的多个复选框的计数

下面的代码如何:

export class AppComponent {
  nestedjson: { value: any[],name: string }[] = [
    { name: "parent1",value: ["child11","child12"] },{ name: "parent2",value: ["child2"] },{ name: "parent3",value: ["child3"] }
  ];
  constructor(){        
    const count = this.nestedjson.map(x => x.value.length).reduce((x,y) => x + y);
  }
}
,

首先使用[(ngModel)]将每个复选框绑定到一个值。这样我们就可以跟踪 复选框的值。

根据您的nestedJson数据,创建一个对象checkboxes,并使用false值填充该对象,以使所有复选框在开始时都未被选中。

组件:

checkboxes = {}; 

ngOnInit() {
  this.nestedjson.forEach(item => {
    if (item.value) {
      item.value.forEach(checkbox => {
        this.checkboxes[item.name] = this.checkboxes[item.name] || [];
        this.checkboxes[item.name].push(false);
      });
    }
  });
}

在模板中,将每个复选框绑定到其各自的值。

模板:

<ul *ngFor="let item of nestedjson">
  <li class="parentNav">parent1</li>
  <li class="childData">
    <ul>
      <li *ngFor="let child of item.value; let i = index">
        {{child}}
        <span class="pull-right">
          <input type="checkbox [(ngModel)]="checkboxes[item.name][i]">
        </span>
      </li>
    </ul>
  </li>
</ul>

要查找计数,请循环访问checkboxes对象属性,然后通过检查复选框是否选中来添加到计数中。

findCount() {
  this.count = 0;
  for (let key in this.checkboxes) {
    if (this.checkboxes[key]) {
      this.checkboxes[key].forEach(checkbox => {
        if (checkbox) {
          this.count++;
        }
      });
    }
  }
}

StackBlitz上的实时演示: https://stackblitz.com/edit/angular-9rzjy7

本文链接:https://www.f2er.com/3162631.html

大家都在问