1

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

2
  • Please post an example. Most Angular form template examples only show the validation messages if the control has been touched or changed; your solution may be as simple as removing these conditions from the validation error message element but we will need an example. Commented Aug 9, 2018 at 6:25
  • added. please check .stackblitz.com/github/vugar005/Angular-NT-Components/tree/… Commented Aug 9, 2018 at 6:47

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It worked ! I actually placed markAsTouched() after patching value of controls.
2

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.