How to store multiple checkbox values in reactive form in angular2?
I liked very much the answer of @yurzui But had an issue with getting the values back .. So..
My solution - solved it for Angular 5 with Material View
The connection is through the
formArrayName="notification"
(change)="updateChkbxArray(n.id, $event.checked, 'notification')"
This way it can work for multiple checkboxes arrays in one form. Just set the name of the controls array to connect each time.
constructor(
private fb: FormBuilder,
private http: Http,
private codeTableService: CodeTablesService) {
this.codeTableService.getnotifications().subscribe(response => {
this.notifications = response;
})
...
}
createForm() {
this.form = this.fb.group({
notification: this.fb.array([])...
});
}
ngOnInit() {
this.createForm();
}
updateChkbxArray(id, isChecked, key) {
const chkArray = < FormArray > this.form.get(key);
if (isChecked) {
chkArray.push(new FormControl(id));
} else {
let idx = chkArray.controls.findIndex(x => x.value == id);
chkArray.removeAt(idx);
}
}
<div class="col-md-12">
<section class="checkbox-section text-center" *ngIf="notifications && notifications.length > 0">
<label class="example-margin">Notifications to send:</label>
<p *ngFor="let n of notifications; let i = index" formArrayName="notification">
<mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>
</p>
</section>
</div>
At the end you are getting to save the form with array of original records id's to save/update.
Will be happy to have any remarks for improvement.
Here is the Gist
One way would be like this:
1) Setup FormArray
fields with false
default values
this.form = this.formBuilder.group({
cities : this.formBuilder.array(this.cities.map(x => !1)),
zip_codes : this.formBuilder.array(this.zip_codes.map(x => !1))
});
2) The template will look like this:
<div *ngFor="let city of cities; let i = index" formArrayName="cities">
<input type="checkbox" [formControlName]="i">
<span>{{city}}</span>
</div>
<div *ngFor="let zipCode of zip_codes; let i = index" formArrayName="zip_codes">
<input type="checkbox" [formControlName]="i">
<span>{{zipCode}}</span>
</div>
3) Submit form
convertToValue(key: string) {
return this.form.value[key].map((x, i) => x && this[key][i]).filter(x => !!x);
}
onSubmit() {
const valueToStore = Object.assign({}, this.form.value, {
cities: this.convertToValue('cities'),
zip_codes: this.convertToValue('zip_codes')
});
console.log(valueToStore);
}
4) Default values
const defaultCities = ["Mohali", "Amritsar"];
const defaultZipCodes = ["456123"];
this.form = this.formBuilder.group({
cities: this.formBuilder.array(this.cities.map(x => defaultCities.indexOf(x) > -1)),
zip_codes: this.formBuilder.array(this.zip_codes.map(x => defaultZipCodes.indexOf(x) > -1))
});
Plunker Example