0

我正在使用 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;
}

4

1 回答 1

0

forEach 内部 return 不会破坏函数执行,这就是为什么你它不起作用,尝试使用 for 或 reduce 而不是 forEach。

试试这个:

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;
}
于 2020-04-30T11:31:07.583 回答