【问题标题】:How To check If My List Of Checkbox is Checked or Unchecked AngularJS 2如何检查我的复选框列表是选中还是未选中AngularJS 2
【发布时间】:2017-08-17 04:23:03
【问题描述】:

我有一个复选框列表。

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")
    }
  }

但这不是合适的方式。我不知道选中或未选中哪个元素。 你能帮我找出使用多个复选框的最佳实践吗?因为我想用服务设置数组。我想要我的代码 可重复使用的。所以我只会改变web api。 提前谢谢你

【问题讨论】:

    标签: javascript angular typescript checkbox


    【解决方案1】:

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

    checkBoxChecked()
    {
        this.documentType.forEach(e => {
            if(e.checked){
                console.log(e.type+' is checked !")
            }
        });
    }
    

    【讨论】:

    • 感谢您的回复。它将出现在每个 if() 语句中。想象一下我在那个数组中有 50 个元素!
    • 每个 if 语句是什么意思?
    • 我的错。我没戴眼镜。谢谢你的回复。它就像一个魅力
    【解决方案2】:
    <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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2019-10-30
      • 2022-01-12
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多