I'm building a reactive form with a FormArray which has FormGroups inside. Each FormGroup has 3 controls, from which two are dropdowns. I'd like to prevent the user to choose the same option multiple times in one of the dropdowns. I wrote a custom validator to achive this. It seems the validator works, because I enter the if clause where I return { 'subCategoryRepetition': true }
, but the form stays valid, the controll's error array is null.
Thanks in advance for any help!
Here's the code:
component.ts
initEditUserDetialsForm() {
this.editUserDetailsForm = this.formBuilder.group({
...
categories: this.formBuilder.array(this.initSavedCategoryArray(this.merchantUserDetails.categories),
checkSubCategoryRepetition.bind(checkSubCategoryRepetition))
});
this.categories = this.editUserDetailsForm.get('categories') as FormArray;
this.removeCategoryDisabled = this.categories.length < 2;
}
initSavedCategoryArray(categories: CategoryDTO[]): FormGroup[] {
let formGroupArray: FormGroup[] = [];
categories.forEach((category, index) => {
if (this.subCategories.length === 0) {
this.subCategories.push(category.subCategory.mainCategory.subCategories);
} else {
this.subCategories.splice(index, 1, category.subCategory.mainCategory.subCategories);
}
formGroupArray.push(
this.formBuilder.group({
mainCategory: [+category.subCategory.mainCategory.mainCategoryId, Validators.required],
subCategory: [+category.subCategory.subCategoryId, Validators.required],
donationPercentage: [category.donationPercentage, [Validators.required, Validators.min(1), Validators.max(100)]]
})
);
});
return formGroupArray;
}
custom.validator.ts
export function checkSubCategoryRepetition(formArray: FormArray) {
let subCategoryIds: number[] = [];
formArray.controls.forEach((formGroup: FormGroup) => {
if (subCategoryIds.includes(+formGroup.controls.subCategory.value)) {
console.log('repetition')
return { 'subCategoryRepetition': true };
}
subCategoryIds.push(+formGroup.controls.subCategory.value);
});
return null;
}
forEach inside return will not break function excution, That's why you it's not working, try to for or reduce instead of forEach.
Try this:
export function checkSubCategoryRepetition(formArray: FormArray) {
let subCategoryIds: number[] = [];
const groups = formArray.controls;
for(let i = 0; i < groups.length; i++){
if (subCategoryIds.includes(+group[i].controls.subCategory.value)) {
console.log('repetition')
return { 'subCategoryRepetition': true };
}
subCategoryIds.push(+group[i].controls.subCategory.value);
}
return null;
}