My answer is about cross field validation in Angular Form (check the documentation here cross-field-validation). I would like to know how to find which field's change has fired the form validator when I am inside the validator function (checkAnno, in the example below). This is my code
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
) {
here I would like to know which is the control that, with its change, has activated the validation of the form
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;
}
};
}
Do you have any ideas how to reach the goal?
If you want to know how to check which field is valid or invalid you can use this
Or this for valid
It will work too