There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not.
Object:
let items = [{
ID: 1,
Name: 'Item A',
Selected: 'Yes'
},
{
ID: 2,
Name: 'Item B',
Selected: 'No'
}]
HTML:
<div *ngFor="let item of modalData.dataItems">
<input type="checkbox" (change)="onItemSelectionChange(item.ID, $event.target.checked)" [checked]="(item.Selected == 'Yes' ? true : false)"> {{item.Name}}<br>
</div>
Component:
private formGroup: FormGroup;
ngOnInit() {
this.formGroup = this.fb.group({
selection: this.fb.array([])
});
}
onItemSelectionChange(id: number, isChecked: boolean) {
const selectionFormArray = <FormArray>this.formGroup.controls.selection;
if (isChecked) {
selectionFormArray.push(new FormControl(id));
} else {
let index = selectionFormArray.controls.findIndex(x => x.value == id)
selectionFormArray.removeAt(index);
}
}
Even though the checkboxes appear checked on the UI, when the form is submitted, the array comes back empty. What am I missing here?
onSave() {
console.log(this.formGroup.value)
}
How can I ensure that the form maintains the initial checkbox selections and not just rely on the [checked]
attribute?