【发布时间】: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