Hamdy
Hamdy

Reputation: 440

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

I have a list of checkbox.

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

I display this array in a list of checkbox on the template :

<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>

back to the component i created the checkBoxChecked method:

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

But this is not the appropriate way. i can't know what element is checked or unchecked. Can you help me to figure out the best practice to work with multiple checkboxs. because i want to set the array with services. and i want my code reusable. so i will change only the web api. thank you in advance

Upvotes: 1

Views: 1071

Answers (2)

Vikas Mahajan
Vikas Mahajan

Reputation: 355

<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

Upvotes: 1

YounesM
YounesM

Reputation: 2317

Since you're binding your checkbox to your objects using [(ngModel)]="type.checked", you already have all the data you need. You'll just have to loop on your array to check what checkbox is checked.

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

Upvotes: 2

Related Questions