我正在使用 FormArray 构建一个反应式表单,其中包含 FormGroups 。每个 FormGroup 有 3 个控件,其中两个是下拉菜单。我想防止用户在其中一个下拉菜单中多次选择相同的选项。我编写了一个自定义验证器来实现这一点。验证器似乎有效,因为我在 if 子句中输入了 return { 'subCategoryRepetition': true }
,但表单保持有效,控件的错误数组为空。
提前感谢您的帮助!
这是代码:
组件.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;
}