In my form, I have a checkbox group named formArray
within my checkboxForm
. The task at hand is to disable the submit button if none of the checkboxes are checked. To achieve this, I created a custom validator for my checkboxForm
and here is my approach:
Ts file
get formReceivedSummons() {
return this.checkboxForm.get('receivedSummons') as FormArray;
}
ngOnInit() {
this.checkboxForm = this.formBuilder.group({
receivedSummons: this.formBuilder.array([])
});
this.getReceivedSummons();
}
getReceivedSummons() {
this.receivedSummonsSubscription = this.inquiryStore.summons$
.subscribe(receivedSummons => {
this.receivedSummons = receivedSummons;
});
}
addCheckboxes() {
this.formReceivedSummons.setValue([]);
this.formReceivedSummons.setValidators([minSelectedCheckboxes(1)]);
this.receivedSummons.data.items.map(x => {
this.formReceivedSummons.push(
this.formBuilder.group({
itemNo: [x.itemNo],
isChecked: false,
}));
});
}
function minSelectedCheckboxes(min = 1) {
const validator: ValidatorFn = (formArray: FormArray) => {
const totalSelected = formArray.controls
.map(control => control.value)
.reduce((prev, next) => (next ? prev + next : prev), 0);
return totalSelected >= min ? null : { required: true };
};
return validator;
}
I included validators in the formArray
by using
this.formReceivedSummons.setValidators([minSelectedCheckboxes(1)]);
This is how it was implemented in the html file
<form [formGroup]="checkboxForm" (ngSubmit)="submitSelectedCheckbox()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroupName]="i">
<input type="checkbox" formControlName="isChecked"> {{summon.value.itemNo}}
</ng-container>
</ng-container>
<button [disabled]="!checkboxForm .valid">submit</button>
</form>
Although I disabled the button in the checkboxForm, enabling it when one checkbox is selected remains an issue. Seeking guidance on resolving this matter.
Update
Based on research findings from Google and other sources, I made adjustments. Here's what I came up with:
addCheckboxes() {
this.formReceivedSummons.setValue([]);
this.receivedSummons.data.items.map(item => {
this.formReceivedSummons.push(
this.formBuilder.group({
itemNo: [x.itemNo]
isChecked: [false, Validators.requiredTrue],
}));
});
}
By employing Validators.requiredTrue
, the button requires two checkboxes to be selected for activation. However, I aim for the functionality where enabling the button only demands at least one checkbox selection.