In this demo the login form username field renders in red after login is clicked, even though the form is reset like this:
submit() {
if (this.form.valid) {
this.onLogin.emit(this.form.value);
this.form.reset();
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.setErrors(null);
}
}
How do we keep the username field from painting red?
You have to add the required validator to your form in order to check the validation otherwise it will always return true for this.form.valid. It should be as follows :
form: FormGroup = new FormGroup({
username: new FormControl('',[Validators.required]),
password: new FormControl('',[Validators.required]),
});
Note : be sure you imported Validators from @angular/forms
import { Validators } from '@angular/forms';
and the error message should not be send from parent element because your are checking for errors when submitting the form so the submit() method should be as follows :
submit() {
if (this.form.valid && this.form.touched) {
this.error = ''
this.submitEM.emit(this.form.value);
}else{
this.error = 'Username or password invalid'
}
}
Note : remove Input decorator for error message because the validation check is done in child component.
error: string | null;