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">
</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.
Aucun commentaire:
Enregistrer un commentaire