I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the log
In my Reactive form, I needed to mark a field as invalid if another field was checked. In ng version 7 I did the following:
const checkboxField = this.form.get('');
const dropDownField = this.form.get('');
this.checkboxField$ = checkboxField.valueChanges
.subscribe((checked: boolean) => {
if(checked) {
dropDownField.setValidators(Validators.required);
dropDownField.setErrors({ required: true });
dropDownField.markAsDirty();
} else {
dropDownField.clearValidators();
dropDownField.markAsPristine();
}
});
So above, when I check the box it sets the dropdown as required and marks it as dirty. If you don't mark as such it then it won't be invalid (in error) until you try to submit the form or interact with it.
If the checkbox is set to false (unchecked) then we clear the required validator on the dropdown and reset it to a pristine state.
Also - remember to unsubscribe from monitoring field changes!