1

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

2 Answers 2

2

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 !")
        }
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your reply. it will be on every if() statement. imagine that i have 50 elements in that array!
What do you mean by on every if statement ?
my bad.i am not wearing my glasses. thank you for you reply. it work like a charm
1
<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.