Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set.
Initializing the form.
constructor(){
this.poeForm = this.fb.group({
imageString: [""],
imageFileName: [""],
}
}
}
Upon saving, the validation for the imageString field is invoked.
saveForm() {
this.profileImgValidator();
this.getFormValidationErrors();
if (this.poeForm.invalid) {
Swal.fire("Please fill in all the required fields");
return;
}
}
The actual logic for setting the value.
profileImgValidator(){
let errors = null;
this.mandatoryFields = //server call it will return value or null
if(this.mandatoryFields){
this.poeForm.get('imageString').setValidators(Validators.required);
}else{
this.poeForm.get('imageString').clearValidators();
}
return errors;
}
Checking by iterating through form controls.
getFormValidationErrors() {
Object.keys(this.poeForm.controls).forEach(key => {
const controlErrors: ValidationErrors = this.poeForm.get(key).errors;
if (controlErrors != null) {
Object.keys(controlErrors).forEach(keyError => {
console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
});
}
});
}