Reputation: 2075
I have a template driven form which fills controls if data is available. But after the controls are filled, the error styles are not applied while validation(using Angular material elements). Error styles are applied only if I touch element or submit form. How can I trigger form validation manually ?
You can check stackblitz:
https://stackblitz.com/github/vugar005/Angular-NT-Components/tree/template-driven-approach
Thanks in advance
Upvotes: 1
Views: 2128
Reputation: 1996
Depending on exact requirements, you may want to just trigger validation on all form controls, there is a markAllAsTouched() method on the NgForm object that can do this:
forceValidation(form: NgForm) {
if (!form.valid) {
form.control.markAllAsTouched();
}
}
Upvotes: 2
Reputation: 4119
Trigger markAsTouched() method explicitly, if there is an error on input control during page load
getErrors(str) {
if (this.ntForm && this.ntForm.controls[str] ) {
const control = this.ntForm.controls[str];
const errors = control.errors;
if (!errors) { return; }
control.markAsTouched();
// remaining code
}
Upvotes: 2