我的答案是关于Angular Form中的跨字段验证(请查看此处的文档跨字段验证(。我想知道当我在验证器函数(checkAnno,在下面的例子中(中时,如何找到哪个字段的更改触发了表单验证器。这是我的代码
ngOnInit() {
this.elaborazioneForm = new FormGroup({
anno: new FormControl('',[Validators.required]),
modello: new FormControl('',[Validators.required]),
tipo: new FormControl('', [Validators.required]),
nProtocollo: new FormControl({ value: null, disabled: true })
},
{validators: this.checkAnno()}
);
}
checkAnno(): ValidatorFn {
return (formGroup: FormGroup) => {
if (
!!formGroup.get('anno').value &&
!!formGroup.get('modello').value &&
Math.abs(parseInt(formGroup.get('modello').value, 10) - parseInt(formGroup.get('anno').value, 10)) >= 2
) {
这里我想知道哪个控件在其更改后激活了表单的验证
formGroup.controls['anno'].setErrors({twoYearsOrMore: true});
formGroup.controls['modello'].setErrors({twoYearsOrMore: true});
return { twoYearsOrMore: true };
} else {
formGroup.controls['anno'].setErrors(null);
formGroup.controls['modello'].setErrors(null);
return null;
}
};
}
你对如何达到目标有什么想法吗?
如果你想知道如何检查哪个字段是有效的或无效的,你可以使用这个
this.form.get('field').invalid
或者这是有效的
this.form.get('field').valid
它也会工作
this.form.controls.field.invalid