Reputation: 1092
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>
Upvotes: 2
Views: 1645
Reputation: 73357
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);
}
}
Upvotes: 2