繁体   English   中英

如何检查我的复选框列表是否已选中或未选中AngularJS 2

[英]How To check If My List Of Checkbox is Checked or Unchecked AngularJS 2

我有一个复选框列表。

documentType: IDocument[] = [
    {
      "type": "A",
      "checked": false,
    },
    {
      "type":"B",
      "checked": false,
    },
    {
      "type":"C"    ,
      "checked": false,
    }];

我在模板的复选框列表中显示此数组:

<ion-list *ngFor="let type of documentType">
  <ion-item >
   <ion-label>{{type.documentTypeName}}</ion-label>
       <ion-checkbox [(ngModel)]="type.checked"            (click)="checkBoxChecked(type.documentTypeName)" disabled="false" ></ion-checkbox>
  </ion-item>
</ion-list>

回到我创建checkBoxChecked方法的组件:

  checkBoxChecked(documentTypeinput)
  {
    if (documentTypeinput =="A")
    {
      console.log("this A");
    }
    else if (documentTypeinput=="B"){
      console.log("B")
    }
    else if (documentTypeinput=="C"){
      console.log("C")
    }
  }

但这不是合适的方式。 我不知道检查或取消选中哪个元素。 你能帮助我找出使用多个复选框的最佳实践吗? 因为我想用服务设置数组。 我希望我的代码可以重复使用。 所以我只会改变网络API。 先感谢您

由于您使用[(ngModel)]="type.checked"将复选框绑定到对象,因此您已经拥有了所需的所有数据。 您只需在数组上循环以检查选中的复选框。

checkBoxChecked()
{
    this.documentType.forEach(e => {
        if(e.checked){
            console.log(e.type+' is checked !")
        }
    });
}
<li *ngFor="let col of data" class="form-group">
   <input type="checkbox" name="col" value=" {{col.value}}" [(ngModel)]="col.value" (change)="addColumns(col)" />{{col.name}}
</li>

 data:any[]=[{"id":"13","name":"AAA"},{"id":"15","name":"BBB"}, {"id":"20","name":"CCC"}]
 constructor() {}
 get selectedcheckboxes() {
     return this.data
       .filter(opt => opt.value)  
 }

addColumns(col){
  this.selectedcheckboxes;
  console.log(this.selectedcheckboxes)
}


 See The demo below using the property binding-ngModel  :

DEMO

暂无
暂无

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

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