【问题标题】:Angular 6 Reactive Forms Custom Validator getting error shown from Default DataAngular 6 Reactive Forms Custom Validator从默认数据中显示错误
【发布时间】:2018-10-18 20:44:57
【问题描述】:

我在 FormGroup 中有一个 FormArray,每个 FormArray 都有多个 FormGroup,可以动态添加它们。

我有一个自定义验证器,它检查每个 FormArray 中的所有数据以验证数据的重复。目前,它也在用自身验证初始数据,这会引发错误。

在检查初始数据时,有什么方法可以限制错误自行抛出。

添加新数据并具有与现有数据相同的值时,它工作正常。

for (let assign of this.additionalAssign) {
      const fg = new FormGroup({
        "payRate": new FormControl(assign.jobRate, Validators.required),
        "position": new FormControl(assign.position, Validators.required),
        "location": new FormControl(assign.location, Validators.required),
        "department": new FormControl(assign.department, Validators.required)
      }); 
      fg.validator = this.jobDataValidator.bind(this);
      this.addPay.push(fg);
    }

验证器:

jobDataValidator(control: FormControl): {[s: string]: boolean} {
        let value = this.getJobLocDeptValidity(control);
        if(value.length > 0){
          return {'sameJobData': true};
        }
        return null;
      }

getJobLocDeptValidity(control: FormControl):any[] {
            let additionalAssignments = this.additionalAssignmentsForm.value.payArray;
            let test = additionalAssignments.filter(item =>  !!control.value.position && item.position ===              !control.value.location && item.location === control.value.location);
            return test;
          }

截图:

Stackblitz 网址:https://stackblitz.com/edit/angular-custom-validator-defaultdata

【问题讨论】:

    标签: angular angular5 angular6 angular-reactive-forms angular-forms


    【解决方案1】:

    为避免在原始数据上标记错误,您可以添加检查以确保表单控件为dirty,这意味着用户已触摸它。

    if(value.length > 0 && control.dirty){
          return {'sameJobData': true};
    }
    

    【讨论】:

    • 您好 Wrokar,该解决方案工作正常,但我有一个新问题。当我对第二行进行更改以使其具有与第一行相同的值时,会显示错误消息,但是当我对第一行中的值进行更改时,除非我再次对其进行更改,否则第二行仍然显示错误?有什么解决办法吗??
    猜你喜欢
    • 2019-03-23
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2021-10-05
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多