【发布时间】:2022-11-03 23:26:56
【问题描述】:
我的回答是关于 Angular 表单中的跨字段验证(查看此处的文档cross-field-validation)。 我想知道当我在验证器函数中时,如何找到哪个字段的更改触发了表单验证器(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; } };}
您对如何实现目标有任何想法吗?
【问题讨论】:
-
为什么你需要知道这个?表单有效或无效,您可以根据表单状态在各个控件上设置错误。
-
谢谢你的回答安德鲁。因为我想知道哪个是我必须出错的控件。在我的例子中,我把它们都弄错了。
-
好的但是为什么你需要知道哪个是你必须出错的控制吗
-
因为我想在负责触发验证器的更改的字段下放置一个 <mat-error> 元素。我想强调导致错误的组件,并且不要在涉及交叉验证的所有字段上设置错误。我希望我更清楚
-
好的,我明白了
标签: angular angular-forms formgroups angular-custom-validators