2

I have multiple checkbox on my view page and I want to access those selected values on form submit. How Can I access it?. I have seen on SO, that we can access checkbox using change event, but it doesn't work for me. Below is my code.

Note : I am using model driven approach (Form Builder), I would like to see answer in model driven way, if possible.

<ion-row>
<ion-col col-sm-6 col-md-6 col-lg-3 col-xl-4 *ngFor="let location of company_data.data.locations; let i=index" [hidden]="location.location_id == location_id_Ref.value">
  <ion-item>
    <ion-label>{{location.location_name}}</ion-label>
    <ion-checkbox value="{{location.location_id}}" (click)="updateCheckedOptions(location, $event)" formControlName="worksites"></ion-checkbox>
  </ion-item>
</ion-col>
</ion-row>
Nitin Pund
  • 1,082
  • 2
  • 9
  • 23
  • look at this it might help you http://stackoverflow.com/questions/43423333/angular-2-how-to-get-the-multiple-checkbox-value – Arun Kumaresh May 19 '17 at 07:07
  • no its not working, getting error `Uncaught (in promise): TypeError: control.registerOnChange is not a function` – Nitin Pund May 19 '17 at 08:08

1 Answers1

2

First of all, you should not use formControlName with your checkboxes, you want to use an formArray just like suggested in the link provided by Arun. Let's just declare an empty formArray to which we push or remove location's.

this.myForm = this.fb.group({
  worksites: this.fb.array([])
})

Then your template we make a slight change from the other example, we swap (change) to (ionChange) instead:

<ion-item>
  <ion-label>{{location.location_name}}</ion-label>
  <ion-checkbox (ionChange)="updateCheckedOptions(location, $event.checked)"></ion-checkbox>
</ion-item>

and updateCheckedOptions function:

updateCheckedOptions(location:Object, isChecked: boolean) {
  const worksites = <FormArray>this.myForm.controls.worksites;
  // if target checked, push to formarray, else remove
  if(isChecked) {
    worksites.push(new FormControl(location));
  } else {
      let index = worksites.controls.findIndex(x => x.value.location_id == location.location_id);
      worksites.removeAt(index);
  }
}

Demo

AT82
  • 71,416
  • 24
  • 140
  • 167
  • Thanks a lot , its working perfectly now, can you suggest some more links where I will get more information on handling user input in ionic 2 – Nitin Pund May 19 '17 at 08:50
  • Sorry can't help you there really, never used ionic myself other than here on SO. The best I can do is to point you to the official docs: http://ionicframework.com/ Sorry, can't be of more help really :( – AT82 May 19 '17 at 14:41