I've had the same question and stumbled upon this thread, so might as well answer here, if anyone else finds this.
My loginForm object like this:
this.loginForm = this.formBuilder.group({ username: ['', [Validators.required, Validators.minLength(3)]], password: ['', Validators.required] });
If a user submits my login form, the login() function is fired. It checks the state of this.loginForm.invalid, if the form is invalid we check for errors.
The function here checks and shows the error directly, but you could also refactor it into a function.
async login() { if (this.loginForm.invalid) { const controls = this.loginForm.controls; if (Object.values(controls).some(control => control.hasError('required'))) { this.showNoticeFn("Please fill in all fields."); return; } if (controls['username'].hasError('minlength')) { this.showNoticeFn("Username is too short!"); return; } return; } // Login logic }
We could also trigger this logic every time changes happen via ngOnChanges
{email:'error'}, Validators.required return an object{required:true}and so on. so you ask aboutcontrol.errors?.emailor aboutcontrol.errors?.required.