How to check how many checkboxes and toggles are selected in 'ionic 2'

#1

Hi,

I am creating an application in ionic2, I have a page in which I have 5 checkboxes with the different label and 2 toggles with the different label and at the end of the page ‘Submit’ button is there.

so my question is:

  1. When to click on the Submit button, I want to check the state of each checkbox whether it is 'checked = true/false’
    Similarly, for toggles whether it is 'checked = true/false’
    i.e. The state of 5 checkboxes and 2 toggles at the same time.

I may do this by using ‘ionChange’, but then I have to write ‘ionChange’ method 5 times and check the status of all the checkboxes. But what I want is. Is there any short way to code, to get the state of all checkboxes at the same time when to click on ‘submit’.

Thanks in advance

#3

@itlr sory i didnt get you… i am not asking about check the state of individual checkboxes…

My question is…
When i clicked on submit button… the submit() function of submit button have to check the state of all checkbox at the same time…

What i want is…

submit() { // here i want to get state of checkbox 1 i.e. true or false // here i want to get state of checkbox 2 i.e. true or false ... // here i want to get state of checkbox 5 i.e. true or false }

#4

Do you have a form object as documented here? The information you want should be trivially available using its value property.

#5

Well, a convenient way is to [(ngModel)]=myvar, then in submit()

submit() {
  if (this.myvar) { ... }
}

for slightly better encapsulation, you may want to use an object to track each checkbox’ state

[(ngModel)]="checkboxStates['myvar']"

in component

constructor () {
  this.checkboxStates = {};
}

submit() {
  for (let prop of this.checkboxStates) {
    ... 
  }
}

also, a few ionChange= isn’t really as bad as it sounds.

#6

@itlr actuly yes… ionChange isn’t really bad…

But what i want is to any shorthand method to get the state of all checkbox inside a submit function…

That means i have to use ionChange upon each checkboxes??

#7

@itlr thnx for answer… i will try the approach suggested by you…and let you know…

I think this [(ngModel)]="checkboxStates['myvar']" seems to be work in my case…

#8

If you make your checkbox list to render in a more data driven fashion, you would only have to type (ionChange)= once.

<ion-checkbox *ngFor="let checkbox of checkboxes" (ionChange)="handleChange($event)"> {{checkbox.label}} </ion-checkbox>

checkboxes being a list of checkbox metadata.

The overhead of repeated binding could be an overhead but you can do it with a bit of event delegation

<div (click)="handleClick($event)">
   <ion-checkbox></ion-checkbox>
   <ion-checkbox></ion-checkbox>
    ... 
   <ion-checkbox></ion-checkbox>
</div>
handleClick($event) {
  // figure out which checkbox is clicked
}

technically, I believe is still cheaper than multiple (ionChange)= or [(ngModel)]=.