计算在Angular 2打字稿中检查了多少个复选框?

时间:2017-11-22 11:49:44

标签: javascript angular typescript checkbox

如何使用打字稿计算Angular 2/4中检查的框数。它应显示选中的复选框的计数,如果未选中,则应减少为0.

我的例子,来自服务器的数据,我循环通过:

我知道如何在Angularjs中使用foreach函数来做到这一点,但是无法理解在Typescript中如何做到这一点,通常我必须用Typescript foreach方法替换角度foreach方法?需要帮助

app.ts

  data = [
     {"name":"jason"},
     {"name":"james"},
     {"name":"josh"},
     {"name":"joshua"}
          ];



calculateChecked = function() {            
 let count = 0;

  angular.forEach(this.data, function(value) {    //don't work in typescript
    if(value.checked)
      count++;
  });

  return count;
   };
  };

app.htm

 <li class="list-group-item" *ngFor="let user of data">
    <input type="checkbox" [ngModel]="user.checked"/>
    {{user.name}}
    </li>


    <p>total checked: {{calculateChecked()}}</p>

应该显示:

enter image description here

如果未选中则应显示0

  <div class="sasha-ui-list" #em *ngFor="let email of emails; let i=index"
   (click)="onAddtoMessage(email)"> <div class="row"> <div class="col-lg-1">
  <input class="magic-checkbox sasha_checkbox" name="emails" type="checkbox" 
  id="{{email.id}}" value="email" [checked]="checkboxFlag"> <label for="
 {{email.id}}"></label> </div> 

3 个答案:

答案 0 :(得分:1)

没有经过测试的代码,但如果数据是一个数组

,这样的东西应该可行
 this.data.map((value) => {
     if(value.checked)
       count++;   
 });

答案 1 :(得分:1)

如下点击,你应该把它变成0,

 changed(){
    this.count = 0;
    this.data.forEach(item=>{
      console.log(item)
      if(item.checked){
        this.count= this.count+1
      }  
    } )
  }


<ul> <li class="list-group-item" *ngFor="let user of data">

<input type="checkbox" [(ngModel)]="user.checked" (ngModelChange)="changed()"/>
{{user.name}}
</li>

LIVE DEMO

答案 2 :(得分:0)

使用for..of循环:

this.count: number = 0;
for (let datum of data) {
 if(dataum.checked) count++;
}

标记为..

<ul> <li class="list-group-item" *ngFor="let user of data">
  <input type="checkbox" [(ngModel)]="user.checked" (ngModelChange)="changed()"/>
{{user.name}}
</li>

<p>total checked: {{count}}</p>