Reputation: 431
I have a form like this:
for (const referential of this.referentials) {
referential.values.forEach(referentialValue => {
const newFormGroup = new FormGroup({
value: new FormControl(referentialValue.value, [Validators.required]),
libelle: new FormControl(referentialValue.libelle, [Validators.required]),
primaryColor: new FormControl(referentialValue.primaryColor),
secondaryColor: new FormControl(referentialValue.secondaryColor),
borderColor: new FormControl(referentialValue.borderColor),
default: new FormControl(false)
});
this.referentialArray.push(newFormGroup);
});
}
this.form.addControl('referentials', this.referentialArray);
this.form.disable();
this.initialValue = this.form.value;
and the html:
<ng-container *ngFor="let _ of referentialArray.controls; let i = index">
<tr [formGroupName]="i">
<td><input type="text"
formControlName="value"></td>
<td><input type="text"
formControlName="libelle"></td>
<td>
<input class="w-full max-w-40"
type="color"
formControlName="primaryColor">
<input class="w-full max-w-40"
type="color"
formControlName="secondaryColor">
<input class="w-full max-w-40"
type="color"
formControlName="borderColor">
</td>
<td class="text-center">
<input type="checkbox"
formControlName="default"
(change)="onChange(i)">
</td>
<td>
<app-equipment-preview [equipment]="equipment"
[primaryColor]="_.get('primaryColor').value"
[secondaryColor]="_.get('secondaryColor').value"
[borderColor]="_.get('borderColor').value"></app-equipment-preview>
</td>
<td *ngIf="isEnabled">
<img class="w-5 cursor-pointer"
(click)="this.deleteLine(i)"
src="../../../../../../assets/icons/bin.svg">
</td>
</tr>
</ng-container>
I would like to add the impossibility of selecting multiple checkboxes, only one is selectable, so I tried this:
public onChange(i): void {
this.form.value.referentials.forEach((val, index) => {
if (i !== index && val.default) {
val.default = false;
}
});
}
this method is called when the user clicks on a checkbox, but it doesn't work, i tried different things with patchValue but nothing works, you have any ideas?
Upvotes: 0
Views: 1130
Reputation: 1843
You can not assign value directly to set. You have to go through the patchValue() or setValue() for it.
public onChange(i: number): void {
(this.form.controls['referentials'] as FormArray).controls.forEach((item: FormGroup, index: number) => {
if (i !== index && item.controls['default'].value) {
item.controls['default'].setValue(false);
}
});
}
Upvotes: 2