I had formArray
checkbox on my checkboxForm
, I need to disabled button submit if no checkbox are checked
, I had implement custom validator on my checkboxForm
, this is what I had tried;
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 had place validators at formArray
which is this.formReceivedSummons.setValidators([minSelectedCheckboxes(1)]);
this is what I had implement in 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>
my checkboxForm button have been disabled, but if I checked one checkbox
it should be enabled, but it didnt. I'm not sure how to solve thw problems, could use some guide and guidance to solve this.
Update
based on my finding in google and So, this is the close I can get,
addCheckboxes() {
this.formReceivedSummons.setValue([]);
this.receivedSummons.data.items.map(item => {
this.formReceivedSummons.push(
this.formBuilder.group({
itemNo: [x.itemNo]
isChecked: [false, Validators.requiredTrue],
}));
});
}
by using Validators.requiredTrue
, it need two checkboxes to be selected, then it will enable the button,but my requirement I need at least one checkbox to be select than it will enable the button submit form